Mail Archives: djgpp/1996/07/20/21:54:55
Reply to message 3412151 from GRBHAT AT UNIGOA on 07/20/96 2:18AM
> i need help with a problem i have with reading files created by ms-dos
>edit in djgpp v2. the relevant part of my c++ code is:
>
>ofstream fin(datafile);
>while (!fin.eof())
> fin >> x1 >> x2;
>
>on i execution i find that the last line is read twice. is there some way
>i can avoid this problem?
I think the problem is that DOS Edit automatically puts an extra carriage
return at the very end of every file it creates. Your program doesn't
check for the success of the 'fin', and as a result, it reads the extra line,
doesn't find anything, and leaves the same values in the variables.
Only then does it detect the EOF in the next pass of the loop. I can think
of three things you can do about this:
1) Use a smarter editor (i.e., not Edit) which doesn't put a c/r at the end of
the file.
2) Manually strip off the c/r with a hexeditor utility.
3) Make your program check to see if 'fin' succeeded before using any
of the values.
There is also a minor bug in DJGPP's i/o functions wherein it sometimes
fails to recognize the EOF in a text file if the last line is "incomplete". I
don't think you are tripping over this bug, but you may want to download
the patch that somebody posted for it--either search DJ's mail archives
or ask somebody on the list who can to find it for you.
I have one other recommendation for you - you can avoid all this mess
completely if you simply read an entire line from the file at a time and
perform the parsing yourself. (Use sscanf() or its C++ equivalent.) Not
only does this avoid any bugs that may be inherent to a particular
compiler (and believe me, there are many, not just in DJGPP), it also
gives your code a lot more robustness and makes it easier for you
yourself to detect and trap errors in user input. Most programmers,
once they progress beyond the rank novice stage, quickly discard
the "simple" means of text i/o and do it themselves. :)
John
- Raw text -