首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

读资料出错

2012-09-23 
读文件出错C/C++ code#include iostream#include fstream#include stringusing namespace stdint t

读文件出错

C/C++ code
#include <iostream>#include <fstream>#include <string>using namespace std;int testfile(string filename){    ifstream infile(filename.c_str());    if (!infile)    {        return 1;    }    else    {        return 0;    }}int main(){    string fileName;    cout << "Enter the filename:" << endl;    cin >> fileName;    int in = testfile(fileName);    cout << in << endl;    return 0;}

这是我写的一个读文件的小程序,但是每次都是输出1,读文件失败
为什么?
还有,这个fileName是不是必须是当前目录下已存在的文件?

[解决办法]
是。读取文件是以exe文件生成的地方算起。
如果是调试运行的话记得设置工作目录。项目上右键->调试->工作目录->XXX
[解决办法]
肯定需要那个文件存在,ifstream是从文件里读取内容,文件都不存在怎么读取呀,ofstream是往文件里面写,如果文件不存的话,它会自动创建的 fstream("file",mode) 第一个参数可以是绝对路径,也可以是相对路径,第二几个参数就是模式, 有 std::ios_base::out std::ios_base::app std::ios_base::in等等。
[解决办法]
肯定是需要文件在本目录中存在的,或者你需要使用绝对路径。最好在打开文件时候写上文件打开的模式。

热点排行