fstream won't create a file [duplicate]

2019-01-09 03:20发布

This question already has an answer here:

I'm simply trying to create a text file if it does not exist and I can't seem to get fstream to do this.

#include <fstream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt");
    file << "test";
    file.close();
}

Do I need to specify anything in the open() function in order to get it to create the file? I've read that you can't specify ios::in as that will expect an already existing file to be there, but I'm unsure if other parameters need to be specified for a file that does not already exist.

3条回答
家丑人穷心不美
2楼-- · 2019-01-09 03:48

You should add fstream::out to open method like this:

file.open("test.txt",fstream::out);

More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/

查看更多
做自己的国王
3楼-- · 2019-01-09 03:54

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}
查看更多
Melony?
4楼-- · 2019-01-09 03:59

You need to add some arguments. Also, instancing and opening can be put in one line:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);
查看更多
登录 后发表回答