Correct option is C
The ios::trunc mode in
C++ file handling is used when opening a file in output mode. If the file
already exists, ios::trunc
erases all its contents (truncates it to zero size) before writing new data.
Important Key Points:
1.
Purpose of ios::trunc Mode:
·
Used with ofstream (output file stream).
·
If the file exists, it deletes all existing content before writing new data.
·
If the file does not exist, it creates a new empty file.
2.
Example Usage of ios::trunc in C++:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file("example.txt", ios::trunc); // Truncates the file to zero
file << "New content after truncation!";
file.close();
return 0;
}
· If example.txt
already exists, its
previous content is erased before writing
"New content after truncation!"
· If example.txt
does not exist, a new file is created.
Knowledge Booster:
· ios::app (append mode) is used when you want to add data without erasing the file content.
· ios::in (input mode) is used for reading from a file.
· Combining ios::trunc with ios::out ensures that the file is always cleared before writing.
·
(a) To open a file in input mode → ❌ Incorrect: ios::trunc is only used with
output mode, not input mode.
·
(b) To open a file in output mode → ❌ Partially correct: ios::trunc is used
along with output mode, but its specific function is
to erase existing content, not just open the file.