arrow
arrow
arrow
What is the use of ios::trunc mode?
Question



What is the use of ios::trunc mode?

A.

To open a file in input mode.

B.

To open a file in output mode.

C.

To truncate an existing file to zero.

D.

More than one of the above

E.

None of the above

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.

Free Tests

Free
Must Attempt

General Science : Subject Test - 01

languageIcon English
  • pdpQsnIcon20 Questions
  • pdpsheetsIcon40 Marks
  • timerIcon15 Mins
languageIcon English
Free
Must Attempt

Chapter Test : General Physics - 01

languageIcon English
  • pdpQsnIcon30 Questions
  • pdpsheetsIcon60 Marks
  • timerIcon18 Mins
languageIcon English
Free
Must Attempt

Indus Valley Civilization

languageIcon English
  • pdpQsnIcon10 Questions
  • pdpsheetsIcon10 Marks
  • timerIcon5 Mins
languageIcon English
test-prime-package

Access ‘BPSC TRE (11-12)’ Mock Tests with

  • 60000+ Mocks and Previous Year Papers
  • Unlimited Re-Attempts
  • Personalised Report Card
  • 500% Refund on Final Selection
  • Largest Community
students-icon
246k+ students have already unlocked exclusive benefits with Test Prime!
Our Plans
Monthsup-arrow