注册 登录
编程论坛 C++教室

[求助]为什么编译通不过

chenkuanyi 发布于 2007-05-04 08:38, 2147 次点击

#include <iostream>
#include <fstream>
using namespace std;
void main(void)
{
ifstream infile("myfile.txt",ios::in|ios::nocreate);
if (!infile)
{
cout<<"文件不存了,不能打开的文件:"<<"myfile.txt"<<endl;
exit(1);
}
}
myfile.txt 是存在的

38.cpp(6) : error C2039: “nocreate”: 不是“std::basic_ios<_Elem,_Traits>”的成

with
[
_Elem=char,
_Traits=std::char_traits<char>
]
38.cpp(6) : error C2065: “nocreate”: 未声明的标识符

为什么啊,还要加什么头文件不成!

[此贴子已经被作者于2007-5-4 8:41:02编辑过]

2 回复
#2
yuyunliuhen2007-05-04 10:00

#include <iostream>
#include <fstream>
using namespace std;
void main(void)
{
ifstream infile("myfile.txt",ios::in|ios::nocreate);
if (!infile)
{
cout<<"文件不存了,不能打开的文件:"<<"myfile.txt"<<endl;
exit(1);
}
}
myfile.txt 是存在的

38.cpp(6) : error C2039: “nocreate”: 不是“std::basic_ios<_Elem,_Traits>”的成

with
[
_Elem=char,
_Traits=std::char_traits<char>
]
38.cpp(6) : error C2065: “nocreate”: 未声明的标识符

为什么啊,还要加什么头文件不成!


ios::nocreate是在C++标准制定之前在<fstream.h>中有定义的。但是因为它跟系统平台相关密切,所以在C++标准中去掉了对它的支持。可以先以只读方式打开文件,判断文件的存在性(即文件是否打开成功)。如果文件不存在,什么也不做;如果文件存在,则关闭文件,然后以写方式打开文件。这样就实现了ios::nocreate表示的功能。

[此贴子已经被作者于2007-5-4 10:16:01编辑过]

#3
yuyunliuhen2007-05-04 10:43

fstream fs(“fname”, ios_base::in);       // attempt open for readif
(!fs) 
{
        // file doesn't exist; don't create a new one
}else
//ok, file exists. close and reopen in write mode
{
fs.close();
fs.open(“fname”, ios_base::out);         // reopen for write
}

You can just do the opposite for ios::noreplace:

fstream fs(“fname”, ios_base::in);// attempt open for readif
(!fs)
{
   // file doesn't exist; create a new one fs.open(“fname”, ios_base::out);
}
else       //ok, file exists; close and reopen in write mode
{
fs.close() fs.open(“fname”, ios_base::out);       // reopen for write
}

1