fstream won#39;t create a file(fstream 不会创建文件)
问题描述
如果文本文件不存在,我只是想创建一个文本文件,而且我似乎无法让 fstream
做到这一点.
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();
}
我是否需要在 open()
函数中指定任何内容才能让它创建文件?我已经读到你不能指定 ios::in
,因为这会期望一个已经存在的文件在那里,但我不确定是否需要为一个文件指定其他参数不存在.
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.
推荐答案
你应该像这样添加 fstream::out 到 open 方法:
You should add fstream::out to open method like this:
file.open("test.txt",fstream::out);
有关 fstream 标志的更多信息,请查看此链接:http://www.cplusplus.com/reference/fstream/fstream/open/
More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/
这篇关于fstream 不会创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:fstream 不会创建文件


基础教程推荐
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09