这是我的一段代码:
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();
我的问题是:
- 如果我替换 # - 行
f1.open("memory.txt", ios::in |ios::out );
文件f1 打不开。为什么? - 如果我用
f1.open("memory.txt", ios::in |ios::trunc );
替换 # - 行 文件f1 打不开。为什么? - 如果我用
f1.open("memory.txt", ios::out |ios::trunc );
替换 # - 行,文件将打开!为什么?
最佳答案
- 您不检查文件是否已成功删除,如果文件不存在,它将失败。
ios::out
必须设置 ref.ios::trunc
如果文件存在则标志删除所有内容,因此无论文件是否存在它都会打开。
关于c++ - 了解以下情况……fstream 何时打开文件以及何时不打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34473435/