fseek on a position beyond EOF does not trigger EOF using feof, how come?

怎甘沉沦 提交于 2019-11-29 04:01:31

Seeking simply does not test for the file's end.

The reason for this is that you perhaps might want to do an fwrite() where you sought to. fseek() can not know what your plans are for after it was called.

Do an fread() after seeking behind the file's end and you will have feof() returning a non-zero value.

feof() is set after an attempt to read fails, so fgets() or fread() before.

Seeking beyond the EOF will enlarge the file after a subsequent write, so this is conformant, contrary to what others believe. See here: fseek

The fseek() function shall allow the file-position indicator to be set beyond the end of existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.

That's why fseek cannot return EOF. You will later get an EOF if you try to read from a position when nothing had been previously written to that position or behind. So this is all correct behavior.

Seeking beyond the end of the file on some operating systems increases the size of the file. As long as there's space to make the file larger, it will never return an error.

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