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!