了解以下情况......当fstream打开文件时,以及何时不打开文件

时间:2015-12-26 17:09:08

标签: 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 个答案:

答案 0 :(得分:1)

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