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

如何读取计算机中的文件

ClarenceC 发布于 2014-02-09 17:59, 461 次点击
int reservefile(string &filename,vector<string>& cont)
{
    ifstream infile;
    infile.close();
    infile.clear();
    infile.open(filename.c_str());
    if(!infile)
        return 1;
    string line;
    while(getline(infile,line)){
        cont.push_back(line);
    }
    infile.close();
    if(infile.eof())
        return 2;
    if(infile.bad())
        return 3;
    if(infile.fail())
        return 4;
}
int main()
{
    vector<string> cont;
    string filename;
    cout<<"enter your file name : "<<endl;
    cin>>filename;
        //检验错误
    switch(reservefile(filename,cont)){
    case 1:
        cout<<"error: can't open : "<<filename<<endl;
        return -1;
    case 3:
        cout<<"error: system failure "<<endl;
        return -1;
    case 4:
        cout<<"error: read failure "<<endl;
        return -1;
    }
    istringstream instr;
    string str;
         //输出每一个单词
    for(vector<string>::const_iterator ip=cont.begin();ip!=cont.end();++ip){
        instr.str(*ip);
        while(instr>>str){
            cout<<str;
        }
            instr.clear();
    }
    return 0;
}
现在希望读取计算机中的文件,如何确定文件的路径?请指教
                                                      谢谢
1 回复
#2
天使梦魔2014-02-16 20:05
文件的路径?
ifstream的参数可以直接接受路径,不写路径为EXE当前目录
 "C:\\wqnmlgb\\wqnmlgb.txt"
1