c - 为什么 fseek 永远不会返回 -1

标签 c linux file fseek

我正在使用 ubuntu 14.04 并尝试读取二进制文件,但 fseek 永远不会因文件大小不足而返回 -1。

为什么会发生这种情况?

#include <stdio.h>

int main() {
    const char *fn = "myfile";
    FILE * fid;
    fid = fopen(fn, "r");
    int flag;
    while(1) {
        flag = fseek(fid, sizeof(float), SEEK_CUR);
        printf("flag: %d\n",flag);
        if(flag)
            break;
    }
}

最佳答案

简短原因:在 fseek 中,查找超出文件大小的位置不会被视为错误。

以下部分引用自man 3 fseek:

RETURN VALUE

The rewind() function returns no value. Upon successful completion, fgetpos(), fseek(), fsetpos() return 0, and ftell() returns the current offset. Otherwise, -1 is returned and errno is set to indicate the error.

ERRORS

EBADF The stream specified is not a seekable stream.
EINVAL The whence argument to fseek() was not SEEK_SET, SEEK_END, or SEEK_CUR. Or: the resulting file offset would be negative.

这意味着:

// This is not an error
int ret_0 = fseek(file, 1, SEEK_END);
assert(ret_0 == 0);
// While this is an error
int ret_1 = fseek(file, -1, SEEK_SET);
assert(ret_1 == -1);

关于c - 为什么 fseek 永远不会返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25833104/

相关文章:

c - 为什么这个程序会出现段错误?

c - 条件在选择排序中的作用?

linux - 在 Yocto ext4 Image 中设置 Linux 功能

linux - 找到我可以用 ALSA 玩 PCM 的所有设备

linux - 在 AF_PACKET 套接字上发送数据

python - 如何打开一个文件进行读写?

java - 通过删除 PRIME ASCII 字符来打印字符串

c++ - 结构中的函数指针

包含所有文件信息的 C++ 文件列表

javascript - Meteor NodeJs base64 转换回文件