c++ - 了解以下情况……fstream 何时打开文件以及何时不打开文件

标签 c++ fstream

这是我的一段代码:

fstream f;
f.open("memory.txt", ios::out|ios::in);//'memory.txt' already exists - I open it

//...(here are some operations performed on file f)...

f.close();
remove("memory.txt");

//             *** Next, I create a file with the same name ***

fstream f1("memory.txt");
f1.open("memory.txt", ios::in |ios::out |ios::trunc);//#

//...(some operations performed on file f1)...

f1.close();

我的问题是:

  1. 如果我替换 # - 行 f1.open("memory.txt", ios::in |ios::out ); 文件f1 打不开。为什么?
  2. 如果我用 f1.open("memory.txt", ios::in |ios::trunc ); 替换 # - 行 文件f1 打不开。为什么?
  3. 如果我用 f1.open("memory.txt", ios::out |ios::trunc ); 替换 # - 行,文件将打开!为什么?

最佳答案

  1. 您不检查文件是否已成功删除,如果文件不存在,它将失败。
  2. ios::out 必须设置 ref.
  3. ios::trunc 如果文件存在则标志删除所有内容,因此无论文件是否存在它都会打开。

关于c++ - 了解以下情况……fstream 何时打开文件以及何时不打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34473435/

相关文章:

c++ - ofstream 不会在文档文件夹中创建文件

c++ - 'R' 在字符串文字的上下文中意味着什么?

c++ - 在编译时计算中使用 GMP

c++ - 可序列化的 Boost 库 header 和仅 header 库

C++在文本文件中的特定字符后插入新行

c++根据数据类型将输入文件中的数据读入3个并行数组

c++ - 在 C++ 中从 Excel 中读取单元格?

C++读取/写入长值到二进制文件

c++ - 为什么 GCC 和 MSVC std::normal_distribution 不同?

c++ - boost::function 静态成员变量