Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move file pointer back by one integer?

Tags:

c++

file

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?

like image 892
user1955184 Avatar asked Oct 10 '13 15:10

user1955184


People also ask

How do I move a file pointer in C++?

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.

Which method is used to set the position of a file pointer?

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.


2 Answers

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.

like image 199
Antonio Avatar answered Oct 21 '22 15:10

Antonio


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.

like image 45
Grzegorz Avatar answered Oct 21 '22 15:10

Grzegorz