5
offset=ftell(ptr)-sizeof(student1);
fseek(ptr,offset,SEEK_SET);
fwrite(&student1,sizeof(student1),1,ptr);

This C code means move the pointer from the current position ftell(ptr) to start of the just read structure block. Am I right?

If I'm right, can I use SEEK_CUR instead of SEEK_SET to go back to start of the structure block in the file?

Please show me how to use SEEK_CUR and go backward to start of the structure block.

I'm newbie to programming. So please kindly help me.

Edit: Thank you for the answers. What I'm trying to do is to search for a keyword (Roll number of a student) and update this student's information (Name,Address,..). The updated datas are replaced the previous datas successfully. Please let me ask one more question. It there any way to insert the new data above the previous data instead of replacing it with old data?

1
  • 4
    Why the downvote? The OP shows effort in the sense of thought, example code and proposes something being unsure about. So for me this looks Ok.
    – alk
    Commented Nov 11, 2012 at 11:12

2 Answers 2

7

This C code means move the pointer from the current position [ ftell(ptr) ] to start of the just read structure block. Am I right?

I think so.

Please show me how to use SEEK_CUR and go backward to start of the structure block.

You can use a negative offset.

#include <stdio.h>

fseek (ptr, -sizeof student1, SEEK_CUR);

Anyway, you should avoid these calls; it could be very slow. Use rather sequential reading.

3
  • 1
    It might be slow indeed. I think they are trying to overwrite part of a file though so it might be better than the alternatives.
    – Will
    Commented Nov 11, 2012 at 11:07
  • Thank you for the answer. What I'm trying to do is to search for a keyword (Roll number of a student) and update this student's information (Name,Address,..). The updated datas are replaced the previous datas successfully. Please let me ask you one more question. It there any way to insert the new data above the previous data instead of replacing it with old data? Commented Nov 11, 2012 at 15:46
  • 1
    @Min Naing Oo: With such files, there is no easy manner to do this. However, you can save the previous data, overwrite it with the new one, and then write the saved data.
    – md5
    Commented Nov 11, 2012 at 15:55
3

try:

fseek(ptr, -sizeof(student1), SEEK_CUR);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.