fstream无法创建文件

31

我只是想在文件不存在的情况下创建一个文本文件,但我似乎无法让 fstream 实现这一点。

#include <fstream>
using std::fstream;

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

我需要在open()函数中指定什么才能让它创建文件吗?我读到过如果指定ios::in会期望已存在的文件,但我不确定是否需要为不存在的文件指定其他参数。


我认为你需要使用:.open("test.txt", fstream::in); - FacundoGFlores
3个回答

28

1
我是否不允许在尚不存在的文件上执行 file.open("test.txt", fstream::in | fstream::out | fstream::binary); 操作? - raphnguyen
6
如果你想让 fstream::in 在一个不存在的文件上工作,你应该添加 fstream::trunc。 - haitaka
2
@haitaka 这是一个解决方法吗?因为它似乎不合逻辑:为了从创建的文件in中创建流,我必须截断该流。 - Oleksa

17

你需要添加一些参数。同时,实例化和打开可以放在同一行:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

3
这可以做到:
#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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接