You are here:

C/FILE POINTER

Advertisement


Question
Hi again,
So i have a simple qustion,(sorry by the english:$), i like to know, if i can after make a(for ex:) fgetc, and my FP is automatic increased, if i need roll back to the lastest position, its possible? Sorry but the i dont know if you can understand my question, because my enlgish, but for example:

I got a file with this line "Hello world", so i need verify if i got 2 consecutives spaces, so i will do a while loop with c=getc(fp), but when i foud the first space, i will try to find the second, but 'w' is not a space, but after getc(fp), my pointer is in 'o', and i need it in 'w', i had tried fp--, but i got segmentation fault:s, so its possible do it?

Sorry one more time, for the giant test, to make a simpli question, but i got serious problems with english:$

tks 4 all
vando

Answer
Yes, you can do this.
But, you must never do fp-- or fp++.

C gives a function called fseek() to reset the read/write pointer in a file.
Here is how you call it:
fseek(fp, 2, SEEK_CUR);
Here, the read/write pointer will go forward by 2 from the current position (SEEK_CUR). If you change 2 to -2, it will go back by 2 characters from the current position.

There are two more macros: SEEK_SET and SEEK_END.
With SEEK_SET, the calculation will happen from the begining of the file.
With SEEK_END, the calculation will happen from the end of the file.
With SEEK_CUR, the calculation will happend from the current position in the file.

Please let me know if you still face problems or if this is not clear.  

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.