Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

It might be a very dumb question but I am modifying someone else's code and it seems I need to read from a file that was opened in append mode. I tried to fseek to the beginning of the file but nothing is being read. I know I can change the mode to rw but I wanted to know why fseek is not working. In the man page it does say write ignores fseek but nothing about read though.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
270 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is just one pointer which initially is at the start of the file but when a write operation is attempted it is moved to the end of the file. You can reposition it using fseek or rewind anywhere in the file for reading, but writing operations will move it back to the end of file.

When you open in append mode, the file pointer is returned to the end of file before every write. You can reposition the pointer with fseek for reading, but as soon as you call a function that writes to the file, the pointer goes back to the end of file.

The answer at Does fseek() move the file pointer to the beginning of the file if it was opened in "a+b" mode? references the appropriate section of the C standard.

Use the "w+" mode if you would like to write to arbitrary places in file. An existing file will be overwritten.

If you would like to append to an existing file initially, but then fseek to arbitrary place, use "r+" followed by

fseek(f, 0, SEEK_END)

Hope it helps..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...