man 条目说 lseek 应该返回 -1 如果结果文件偏移量对于常规文件是负数。

为什么这样的代码有效?

int fd;
off_t offset;

fd = open("test.txt", O_RDWR);
offset = lseek(fd, -10, SEEK_SET);

printf("%d\n", offset);                // prints -10

if (offset == (off_t) -1)
    perror("seek");                    // error not triggered

我觉得我应该将 offset=-1errno 设置为 EINVAL

这也会导致文件大小显得非常大(接近 unsigned int 的大小) - 似乎是一个溢出问题。这是为什么?

最佳答案

我设法重现了您的“错误”行为。您必须包含 unistd.h 才能获得正确的原型(prototype)。使用此包含,lseek 的行为与所述相同。
当你错过这个包含时,编译器传递一个 int -10 而不是 off_t -10 。这会导致您观察到的行为。
更新:
所需包括的完整列表是

  • open(2)
      #include <sys/types.h>
      #include <sys/stat.h>
      #include <fcntl.h>
    
  • lseek(2)
      #include <sys/types.h>
      #include <unistd.h>
    
  • printf(3) ,
    perror(3)
      #include <stdio.h>
    
  • 10-07 16:26