Here is my code.

if(fseek(file,position,SEEK_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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top