File Streams

Understanding ios::trunc Mode

What is the significance of std::ios::trunc mode?

Abstract art representing computer programming

The std::ios::trunc mode in C++ is used to truncate a file's content when it is opened. This means that if the file already exists, its existing content will be deleted, and the file will start with a size of zero.

This mode is particularly useful when you want to create a new file or completely overwrite an existing file's content.

Here's an example of how to use std::ios::trunc:

#include <fstream>
#include <iostream>
#include <string>

int main() {
  std::ofstream file;
  file.open(
    "example.txt",
    std::ios::out | std::ios::trunc
  );

  if (!file.is_open()) {
    std::cerr << "Failed to open file.\n";
    return 1;
  }

  file << "This is new content.\n";
  file.close();

  std::ifstream readFile("example.txt");
  std::string content;
  while (std::getline(readFile, content)) {
    std::cout << content << '\n';
  }
  readFile.close();
}
This is new content.

In this example, we open example.txt with std::ios::out | std::ios::trunc. The std::ios::trunc mode ensures that any existing content in the file is removed, and we write new content to the file.

Key points about std::ios::trunc:

  • Overwrites Content: When you open a file with std::ios::trunc, any existing content in the file is immediately erased. This is useful when you need to ensure that the file starts fresh each time it is opened.
  • Default Behavior for Output Streams: When you open a file with std::ios::out (output mode), std::ios::trunc is the default behavior unless you specify otherwise. This means that simply opening a file with std::ios::out will typically truncate its content.

Using std::ios::trunc is essential when you want to guarantee that no old data remains in the file, which can be crucial for creating logs, saving new configuration files, or any scenario where starting with an empty file is necessary.

Be cautious when using std::ios::trunc, as it will irreversibly delete all previous content in the file. Ensure this behavior is what you intend to avoid accidental data loss.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved