-3

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.

0

1 Answer 1

3

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:

  • change ifstream fichier(dir); to ifstream fichier;
//ifstream fichier(dir);
ifstream fichier;
fichier.open(dir);
  • remove fichier.open(dir); after ifstream fichier(dir);
ifstream fichier(dir);
//fichier.open(dir);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.