Home >Backend Development >C++ >How to Append Text to Files in C ?

How to Append Text to Files in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 16:52:111009browse

How to Append Text to Files in C  ?

Appending Text to Text Files in C

In C , appending text to a text file requires understanding the appropriate open mode. When aiming to create a new text file if it doesn't exist and append text to it if it does, specify the append open mode: std::ios_base::app.

The following code snippet demonstrates this:

#include <fstream>

int main() {
  std::ofstream outfile;
  outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
  outfile << "Data";  // Appends "Data" to the file
  return 0;
}

In this code, the outfile is opened with std::ios_base::app mode, ensuring that it appends to the existing "test.txt" file if it exists and creates a new one if it doesn't. Subsequently, the text "Data" is written to the file using the << operator.

The above is the detailed content of How to Append Text to Files in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn