■p33,L4 读者来函: 我买了先生出版的 Essential C++ 和 C++ Primer,其中有一段程式码是这样的 (在 C++ Primer 1102页,和 Essential C++ 1.7节内) #include <fstream> using namespace std; void main() { ... fstream io("word.txt", ios_base::in | ios_base::app); ... } 编译与连结皆无问题,但以 ios_base::in 和 ios_base::app 两个叁数所执行的 io(fstream 物件)却无法开启 word.txt 并对它进行读写,我用的是 VC6。这是 VC 的问题还是 C++ 本身语法中叁数搭配的问题? 之後我发现 将此行程式码改为如下 fstream io("word.txt", ios_base::in | ios_base::app | ios_base::out ); 就能正常的开启word.txt 请帮忙解答,谢谢。这个错误是我上课时学生发现的,之後我再加以测试的结果。 侯捷回覆: 我写了一个小程式测试之,并加上注解,如下。 #include <fstream> #include <iostream> using namespace std; int main() { // 注:书上只有 ios_base::in | ios_base::app fstream io("word.out", ios_base::in | ios_base::app | ios_base::out); if (!io) { cout << "can not open"; exit(-1); } int i; io >> i; cout << i << endl; io << 23; io << 28; // 写是写了,将来如何读出?因此还需总体格式上的考量。这里不考虑那麽多。 } /* 注意,观察档案内容时,以 type word.out 是不准确的。 应使用诸如 tdump.exe 之类的 binary dumper. 在 VC6 中,无法正确开起档案,除非加上 ios_base::out。 但即使加上 ios_base::out,也无法顺利 append. 在 CB5 中,可顺利开启档案并读资料,但却无法顺利而正确地 append, 必须加上 ios_base::out 才可顺利 append。 在 G291 中无法编译。 */ 感谢:Tse-Chen Yeh 日期:2002/12/13