Say I have a file containing integers in the form
1 57 97 100 27 86 ...
Say that I have a input file stream fin and I try to read the integers from the file.
ifstream fin("test.txt");
int val;
fin>>val;
Now I am doing this action in a while loop where at one period of time, I want to move my file pointer exactly one integer back. That is if my file pointer is about to read the integer 27
when I do fin>>val
, I want to move the file pointer such that it can read the integer 100
when I do fin>>val
. I know we can use fin.seekg()
but I have used it only to move the file pointers by characters, not by integers.
Probably this is a naive question. But can someone please help me out?
fseek() is used to move file pointer associated with a given file to a specific position. position defines the point with respect to which the file pointer needs to be moved. It has three values: SEEK_END : It denotes end of the file.
The seek() function sets the position of a file pointer and the tell() function returns the current position of a file pointer. A file handle or pointer denotes the position from which the file contents will be read or written. File handle is also called as file pointer or cursor.
You can use tellg
after each read to save the pointer to be used later on with a seekg
.
You could also take the implementation of <<
and modify it with a function that also returns the number of characters you have advanced each time. Where to find the source code of operator<<
is not something where I could easily help you with.
In your case it is not an integer, but a text representing a number. Because of this you will have to move backward character by character until you find a non-digit one (!isdigit(c)
).
As one of the commenters below pointed out, you may also pay attention to a the 'minus' sign in case your numbers can be negative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With