c - 在c中使用lseek命令获取文件大小

标签 c operating-system

我被要求使用 usjng lseek 命令(不使用 stat)查找文件的大小,我编写了以下代码

int main()
{
    字符 buf[100], fn[10];
    int fd,我;
    printf("请输入文件名\n");
        scanf("%s", fn);
    fd = open(fn, O_RDONLY);
    int size = lseek(fd, 0, SEEK_END);
    printf("大小为 %d", size);
    关闭(fd);
}

但是我得到的文件大小是-1,我哪里出错了

最佳答案

来自 lseek 文档可用 online :

RETURN VALUE        
Upon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. On error, the value (off_t) -1 is returned and errno is set to indicate the error.

所以你必须检查 errno(如果 lseek 返回 -1 则打印它):

来自同一 link 的可能错误列表:

ERRORS

   EBADF  fd is not an open file descriptor.  
   EINVAL whence is not valid.  Or: the resulting file offset would be
          negative, or beyond the end of a seekable device.  
   ENXIO  whence is SEEK_DATA or SEEK_HOLE, and the file offset is
          beyond the end of the file.  
   EOVERFLOW  The resulting file offset cannot be represented in an off_t.  
   ESPIPE fd is associated with a pipe, socket, or FIFO.  

在您的情况下,很可能是 EBADF。

关于c - 在c中使用lseek命令获取文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52050495/

相关文章:

c++ - 想要在 C++ 中创建一个存储 Nx3 值的 2D 指针

c - 为什么同一个程序第一次执行后速度快很多

c - 停止程序的简单有效方法

C汇编编程

c - 编写符合 POSIX 标准的内核

C++ 内存管理和虚拟内存页面大小

memory - I/O映射的I/O-端口地址是RAM的一部分

linux - linux中ps和ps -e命令有​​什么区别

linux - "zero copy networking"与 "kernel bypass"?

c++ - 传递 malloc 指针给我错误