Writing a string to the end of a file (C++)

后端 未结 4 2212
逝去的感伤
逝去的感伤 2021-02-12 16:06

I have a program already formed that has a string that I want to stream to the end of an existing text file. All of what little I have is this: (C++)

 void main(         


        
相关标签:
4条回答
  • 2021-02-12 16:31

    Open your stream as append, new text written to it will be written at the end of the file.

    0 讨论(0)
  • 2021-02-12 16:37

    Open your file using std::ios::app

     #include <fstream>
    
     std::ofstream out;
    
     // std::ios::app is the open mode "append" meaning
     // new data will be written to the end of the file.
     out.open("myfile.txt", std::ios::app);
    
     std::string str = "I am here.";
     out << str;
    
    0 讨论(0)
  • 2021-02-12 16:40

    To append contents to the end of files, simply open a file with ofstream (which stands for out file stream) in app mode (which stands for append).

    #include <fstream>
    using namespace std;
    
    int main() {
        ofstream fileOUT("filename.txt", ios::app); // open filename.txt in append mode
    
        fileOUT << "some stuff" << endl; // append "some stuff" to the end of the file
    
        fileOUT.close(); // close the file
        return 0;
    }
    
    0 讨论(0)
  • 2021-02-12 16:40

    I hope that isn't your whole code because if it is, there's lots of things wrong with it.

    The way you would write out to a file looks something like this:

    #include <fstream>
    #include <string>
    
    // main is never void
    int main()
    {
        std::string message = "Hello world!";
    
        // std::ios::out gives us an output filestream
        // and std::ios::app appends to the file.
        std::fstream file("myfile.txt", std::ios::out | std::ios::app);
        file << message << std::endl;
        file.close();
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题