开发者

Problem with fseek

Here is my code.

if(fseek(file,position,SE开发者_C百科EK_SET)!=0)
{
  throw std::runtime_error("can't seek to specified position");
}

I used to assume that even if position is greater than num of characters in file this code would work correct (i.e. throw error), but it wouldn't. So I want to know how can I handle seeking failure when trying to seek out of file range?


Well, you can always check for file length before doing the fseek.

void safe_seek(FILE* f, off_t offset) {
    fseek(f, 0, SEEK_END);
    off_t file_length = ftell(f);
    if (file_length < offset) {
        // throw!
    }
    fseek(f, offset, SEEK_SET);
}

Be aware though that this is not thread safe.


if( fseek(file,position,SEEK_SET)!=0 || ftell(file) != position )
{
  throw std::runtime_error("can't seek to specified position");
}


According to man: http://linuxmanpages.com/man3/fseek.3.php, fseek returns non-zero value in case of an error, and the only errors that may appear are:

EBADF The stream specified is not a seekable stream.
EINVAL The whence argument to fseek() was not SEEK_SET, SEEK_END, or SEEK_CUR.

Falling beyond the end-of-file is probably considered not an error for lseek. However, calling feof immediately after may indicate the out-of-file condition.


It's not an error to seek past the end of the file. If you write to that offset, the file will be extended with null bytes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜