ifstream won't open file

拟墨画扇 提交于 2019-12-14 01:30:32

问题


I'm trying to open a file so I can read from it.

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

ifstream input_file("blah.txt", ios::in);
ofstream output_file("output.txt", ios::out);

Bank::Bank(void){
    input_file.open("blah.txt");
    if(!input_file){
        cerr << "Error" << endl;
        exit(1);
    }
    else{
        cout << "good 2 go" << endl;
    }
}

This is the code I have for reading the file named blah.txt and the output I'm getting at the terminal is the "Error". I am using Linux Mint 14 and gVim, so when I enter the :pwd command, I know I am in directory /mnt/share. Checking from the terminal, file blah.txt is in the same directory. The only thing I can think of is hidden file extensions. Why can't I open the file?


回答1:


That's because you open "blah.txt" twice.

First time:

ifstream input_file("blah.txt", ios::in)

Second time:

input_file.open("blah.txt")

Removing the second one should fix your problem.




回答2:


This

ifstream input_file("blah.txt", ios::in);

should open the file:

Additionally, when the second constructor version is used, the stream is associated with a physical file as if a call to the member function open with the same parameters was made.

This

input_file.open("blah.txt");

should fail:

If the object already has a file associated (open), the function fails.

Please read the documentation.



来源:https://stackoverflow.com/questions/14920106/ifstream-wont-open-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!