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?