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

How to Append Text to Files in C ?

Linda Hamilton
Release: 2024-12-05 16:52:11
Original
985 people have browsed it

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template