C++ fstream 不会创建文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15667530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:36:32  来源:igfitidea点击:

fstream won't create a file

c++file-iofstream

提问by raphnguyen

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

我只是想创建一个文本文件,如果它不存在,我似乎fstream无法做到这一点。

#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::inas 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.

我是否需要在open()函数中指定任何内容才能让它创建文件?我已经读到您不能指定,ios::in因为这会期望已经存在的文件存在,但我不确定是否需要为尚不存在的文件指定其他参数。

采纳答案by haitaka

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

您应该将 fstream::out 添加到 open 方法中,如下所示:

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

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

有关 fstream 标志的更多信息,请查看此链接:http: //www.cplusplus.com/reference/fstream/fstream/open/

回答by ceruleus

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);

回答by Ritesh Kumar Gupta

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();
}