Home >Backend Development >C++ >How Do I Append Text to a File in C ?

How Do I Append Text to a File in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 06:43:10785browse

How Do I Append Text to a File in C  ?

Appending Text to Text Files in C

Appending text to a text file in C is a common task. It allows you to add new content to an existing file without overwriting its existing contents. Additionally, you can also create a new text file if it does not exist and append text to it.

To achieve this, you can utilize the following steps:

1. Open the File

Open the text file using std::ofstream with the appropriate open mode. In this case, specify the append open mode using std::ios_base::app. This mode allows you to append data to the end of the file if it exists or create a new file if it does not:

#include <fstream>

int main() {  
  std::ofstream outfile;

  outfile.open("test.txt", std::ios_base::app); // append instead of overwrite

2. Append Text

Once the file is open, you can use the << operator to append text to the end of the file:

outfile << "Data"; 

3. Close the File

Finally, close the file to save the changes:

  return 0;
}

This code will open the file "test.txt" in append mode, append the string "Data" to the end of the file, and close the file. If the file does not exist, it will be created with the specified text.

The above is the detailed content of How Do I Append Text to a File 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