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

How to Append Text to a File in C ?

DDD
Release: 2024-12-09 03:26:10
Original
1037 people have browsed it

How to Append Text to a File in C  ?

Appending Text to Text Files in C

In C , appending text to a text file requires managing open modes. You can create a new text file if it does not exist and append text to it if it does exist by utilizing the append open mode.

Solution:

The following C code demonstrates how to append text to a text file:

#include <fstream>

int main() {
    std::ofstream outfile;

    // Open file in append mode
    outfile.open("test.txt", std::ios_base::app);

    // Append data to file
    outfile << "Data";

    // Close the file
    outfile.close();

    return 0;
}
Copy after login

By specifying the std::ios_base::app mode in outfile.open, the file will be opened for appending instead of overwriting. The outfile << "Data" statement then appends the "Data" string to the file.

Remember to close the file using outfile.close() when finished to ensure data is written to the disk.

The above is the detailed content of How to Append Text to a File 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template