c++fstreamreadfileifstream

How to solve problem when reading from a file in c++


I'm trying to read the information from a .txt file but something very strange is happening.

Here's the code:

ifstream fichier(dir);
fichier.open(dir);
     
if (fichier.is_open())
    cout << "file is opened";

double a;
fichier >> a;

I can see on the screen the sentence "file is opened" but nothing is assigned to "a". The file is not empty, I already verified that.


Solution

  • ifstream fichier(dir);

    In this statement, you are passing the filename to the constructor, so it opens the file immediately.

    fichier.open(dir);

    And then, in this statement, you are passing the filename to open(), so it tries to open the same file again and fails, putting the stream into an error state which you are not clearing. That is why fichier >> a does not read anything afterwards.

    A file stream can't have two file handles open at the same time. If it already has a file open, you need to close() it before you can open another file with it.

    The simplest solution is to just not open the stream twice to begin with. Either:

    //ifstream fichier(dir);
    ifstream fichier;
    fichier.open(dir);
    
    ifstream fichier(dir);
    //fichier.open(dir);