Vishal Sharma
Vishal Sharma

Reputation: 1750

Behaviour of static ifstream object inside a function

I've made a static ifstream object inside a function and I'm associating it with the file given in the function argument.

In the main function, I'm calling this function twice, each time with a different file name.

Here's my code:

#include <iostream>
#include<fstream>

using namespace std;

void print_file(string path)
{
  static ifstream ifs{path.c_str()};
  if (ifs.is_open())
  {
    cout<<endl<<"Going to print the file: "<<endl;
    char c = ifs.get();
    while (ifs.good()) {
      std::cout << c;
      c = ifs.get();
    }
  }
  else
    cout<<endl<<"File couldn't be opened"<<endl;
}

int main(int argc, char**argv)
{
if(argc!=3)
{
cout<<endl<<argv[0]<<" file_name1 file_name2"<<endl;
return 0;
}

print_file(argv[1]);
print_file(argv[2]);
}

Given below is the output:

[vishal1@localhost temp]$ ./exe file1.txt file2.txt

Going to print the file:
File 1 contents

Going to print the file:

Due to some reasons file1 is not getting printed the second time. What's the reason?

Upvotes: 1

Views: 88

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

The reason is that in the first call you read all the contents of the file, but you're not resetting the read file pointer to the beginning. So the next call the file status is still and the end of the file and ifs.good() returns false.

You need to "rewind" the file, and clear the status flags.


Also note that you should never use eof() in a loop condition, and using good() is just the same.

In your case, use e.g.

while (ifs.get(c))
{
    std::cout << c;
}

instead.

Upvotes: 3

Related Questions