c++ - 无法使用 fstream 打开新的进出文件

标签 c++ fstream

我想用 fstream 打开一个新的可读可写文件。我尝试像下面的代码那样做,但失败了,因为该文件不存在。

file.open(file_path, ios::in | ios::out | ios::binary);

有什么好的方法可以对新文件执行此操作吗?

我写了下面的代码,但看起来很难看。

    file.open(file_path, ios::out | ios::binary);
    file.close();
    file.open(file_path, ios::in | ios::out | ios::binary);

最佳答案

如果你想覆盖已经存在的文件,你应该使用:

file.open(file_path, ios::in | ios::out | ios::binary | ios::trunc);

附加到这样的文件:

file.open(file_path, ios::in | ios::out | ios::binary | ios::app);

关于c++ - 无法使用 fstream 打开新的进出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34240384/

相关文章:

c++ - 如何分 ionic 模板类的定义和声明

C++ ifstream 跳过数据

C++/fstream : cannot create a new file

c++ - extract>> 运算符在 C++ 中究竟是如何工作的

C++ fstream - 无法使用二进制格式从文件中读取

c++ - 在卡萨布兰卡中实现多个 API

c++ - 我可以在头文件中省略智能指针的类型参数吗?

c++ - std::forward 是如何工作的?

c++ - 将整数写入二进制文件 C++ 的问题

c++ - 从文件中读取空格分隔的数字直到换行符