c++ - Can't get ios::beg to go back to the beginning of the file -
it seems things should no problem cause problems me. don't it. :/
so i'm trying make sure understand how manipulate text files. i've got 2 files, "infile.txt" , "outfile.txt". "infile.txt" has 6 numbers in , nothing else. here code used manipulate files.
#include<fstream> using std::ifstream; using std::ofstream; using std::fstream; using std::endl; using std::ios; int main() { ifstream instream; ofstream outstream;//create streams instream.open("infile.txt", ios::in | ios::out); outstream.open("outfile.txt");//attach files int first, second, third; instream >> first >> second >> third; outstream << "the sum of first 3 nums " << (first+second+third) << endl; //make 2 operations on 6 numbers instream >> first >> second >> third; outstream << "the sum of second 3 nums " << (first+second+third) << endl; instream.seekg(0); //4 different ways force program go beginning of file //2. instream.seekg(0, ios::beg); //3. instream.seekg(0, instream.beg); //4. instream.close(); instream.open("infile.txt"); //i have tried 4 of these lines , #4 works. //there has got more natural option //closing , reopening file. right? instream >> first >> second >> third; outstream << "and again, sum of first 3 nums " << (first+second+third) << endl; instream.close(); outstream.close(); return 0; }
maybe don't understand quite how stream works, i've seen few sources said seekg(0) should move index start of file. instead, out of it.
the sum of first 3 nums 8
the sum of second 3 nums 14
and again, sum of first 3 nums 14
it went back, not in way have hoped. idea why happened? why did first 3 attempts fail?
as bo persson states, may because input has encountered end of file; shouldn't, because in c++, text file defined being terminated '\n'
, practically speaking, if you're working under windows, lot of ways of generating file omit final '\n'
—although formally required, practical considerations mean you'll make sure works if final '\n'
missing. , can't think of other reason off hand why seekg
's wouldn't work. instream.seekg( 0 )
is, of course, undefined behavior, in practice, work pretty everywhere. instream.seekg( 0, ios::beg )
guaranteed work if instream.good()
, , is, imho, preferable first form. (the single argument form of seekg
used results of tellg
argument.) , of course, works if actual input source supports seeking: won't work if you're reading keyboard or pipe (but presumably, "infile.txt"
neither).
in general, should check status of instream
after each read, before using results. if problem file doesn't end '\n'
, it's probable status ok (!fail()
) after final read, if you've encountered end of file. in case, you'll need clear()
anyway.
note above comments valid c++-03 , precedent. c++11 has changed specification of single argument form of seekg
, , requires reset eofbit
before else. (why change single argument form of seekg
, , not 2 argument form? oversight?)
Comments
Post a Comment