behaviour of fseek and SEEK_END

点点圈 提交于 2019-12-24 14:27:29

问题


If I have a text file with the following content opened as binary

1234567890

a call like this:

fseek(fp, 5L, SEEK_SET);

give me 6 when I call (char)fgetc(fp) because I offset 5 byte from byte 0 (not start from 1 but from 2)

but If I do:

fseek(fp, -3L, SEEK_END);

give me 8 and not 7 when I call (char)fgetc(fp).

Why? It seems as with SEEK_END the offset doesn't start from the previous byte after the last.


回答1:


SEEK_END searches from the one-past last byte of the file:

1234567890   <--- bytes from the file
0123456789A  <--- SEEK_SET-relative position
A9876543210  <--- SEEK_END-relative position (absolute value)
          ^
          This is the (0, SEEK_END) byte

With this in mind, the very last byte of the file is the one found at (-1, SEEK_END) and thus the (-3, SEEK_END) byte is the 8.

Note that this is consistent with how C usually handles this kind of thing. For example a pointer to the end of a memory block will usually point to one-past the last byte of that block.

This also has the nice feature that you can get the size of the file with a call to fseek(SEEK_END) plus ftell(). No need to add or substract 1!

The man page from fseek() is a bit ambiguous about this issue, but compare with the man lseek that contains the same issue:

If whence is SEEK_END, the file offset shall be set to the size of the file plus offset.

In your example the size of the file is 10, and the offset is -3, so the final position is 10-3 = 7. And in offset 7 there is an 8.




回答2:


I think is because of the last character of file is '\n' or '\0' or something like that.




回答3:


fseek allows appending texts to a current file. Therefore the filepointer is set after (!) the last character in the file, because that is the place where new characters are to be appended.

From the start:

01234         <---position
ABCDEFGHIJK   <---file content

From the end:

       43210  <---position
ABCDEFGHIJK   <---file content

So when you are fetching from the start, the 0th character is the A And the 3rd is D.

But when you are fetching from the end, the 0th characters is EndOfFile And the -3rd is I.



来源:https://stackoverflow.com/questions/27549718/behaviour-of-fseek-and-seek-end

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!