问题描述
- c++ primer 习题8.6 文件总是打开失败
-
#include "stdafx.h"
#include
#include
#include
using namespace std;
istream &f(istream &);int _tmain(int argc, _TCHAR* argv[])
{
string filename="hello";
ifstream input;
input.open(filename.c_str(),ios::binary);
if(input.is_open())
{
cout<<"opened"<<endl;
}
if(!input)
if(input.bad())
cout<<"bad"<<endl;
if(input.fail())
cout<<"fail"<<endl;
return -1;
f(input);
system("pause");
return 0;
}istream &f(istream &in)
{
string temp;
while(in>>temp,!in.eof())
{
if(in.bad())
throw runtime_error("IO stream corrupted");
if(in.fail())
{
cerr<<"bad data,try again!";
in.clear();
in.setstate(istream::eofbit);
continue;
}
cout<<temp<<endl;
}
in.clear();
return in;}
代码如上,总是跳到文件打开失败语句,hello.txt文件我放在与exe文件同一个目录下。
百思不得其解啊?为什么呢?
解决方案
《c++ primer》 习题3.13-3.16
C++ Primer 第11章 习题11.9
C++ Primer习题5.18
解决方案二:
终于在我的不懈努力下,解决这个问题啦!!!!还是文件路径的问题,把它改成绝对路径就可以了,但是还是不明白放到Debug文件夹为什么不可以?
解决方案三:
你文件名是hello,怎么没有.txt
既然绝对路径可以,那么就是你exe跟文件得相对路径没有处理对。
解决方案四:
不是啊,一般写程序不用绝对路径的。你的文件就写错了吧