简体   繁体   中英

Create and write in a file in c++

I want to create a file and write something inside. so I wrote this:

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, const char * argv[])
{
    ofstream m;
    m.open("bonjour.txt");
    m << "bonjour.\n";
    m.close();
    return 0;
}

And I think that this is correct, but when I execute it, I find no file bonjour.txt. Have I done something wrong?

There is no issue with the code. It works for me and file "bonjour.txt" created with content "bonjour".

ofstream m("bonjour.txt", ios_base::app);

with the use of the append mode you can open and close your file as many times as you want and it won't erase the content that was in the text file previously. This is reference to the ios_base::openmodes http://www.cplusplus.com/reference/ios/ios_base/openmode/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM