C++ File IO bugs -- can't read file twice?
This is a project I've started working on...this code is just an example but it's essential for my project. The point is to repeatedly read through the same file over and over again, applying small changes to it depending on certain conditions. However, I get errors the 2nd time around. I simplified that part of the code and wrote this program:
// This is file test.cpp
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
ifstream ifs;
for(int i = 0; i < 2; i++) {
ifs.open(argv[1],ios::in);
if(!ifs) { cerr << "error" << endl; return 0; }
string line;
while(getline(ifs,line))
cout << line << endl;
ifs.close();
}
return 0;
}
Compiles just fine: g++ -o test test.cpp
when I run ./test test.cpp (i.e. it will display the contents of file test.cpp twice onto cout)
I get this:
$ ./test test.cpp
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
ifstream ifs;
for(int i = 0; i < 2; i++) {
ifs.open(argv[1],ios::in);
if(!ifs) { cerr << "error" << endl; return 0; }
string line;
while(getline(ifs,line))
cout << line << endl;
ifs.close();
}
return 0;
}
error
$
So it's reading the file once, and then freaking out the 2nd time...why? This seems logical but I'm missing something obviously....
|