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

时间:2018-08-28 05:09:47

标签: c operating-system

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

int main()
{
    char buf[100], fn[10];
    int fd, i;
    printf("Enter file name\n");
        scanf("%s", fn);
    fd = open(fn, O_RDONLY);
    int size = lseek(fd, 0, SEEK_END);
    printf("Size is %d", size);
    close(fd);
}

int main() { char buf[100], fn[10]; int fd, i; printf("Enter file name\n"); scanf("%s", fn); fd = open(fn, O_RDONLY); int size = lseek(fd, 0, SEEK_END); printf("Size is %d", size); close(fd); }

但是我的文件大小为-1,我在哪里出错

2 个答案:

答案 0 :(得分:1)

来自onlinelseek文档中:

  

返回值
         成功完成后,lseek()返回结果偏移量          从文件开头算起的位置(以字节为单位)。 开启          错误,则返回值(off_t)-1并设置errno以指示          错误。

因此,您必须检查errno(如果lseek返回-1,请打印它):

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

  

错误

   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。

答案 1 :(得分:0)

以下建议的代码:

  1. 干净地编译
  2. 正确检查错误
  3. 执行所需的功能
  4. 使用正确的变量类型

现在是建议的代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int main( void )
{
    char fn[10];
    int fd;
    printf("Enter file name\n");
    if( scanf("%9s", fn) != 1 )
    {
        fprintf( stderr, "scanf for file name failed\n" );
        exit( EXIT_FAILURE );
    }

    if( (fd = open(fn, O_RDONLY) ) < 0 )
    {
        perror( "open failed" );
        exit( EXIT_FAILURE );
    }

    off_t  size = lseek(fd, 0, SEEK_END);
    printf("Size is %ld", size);
    close(fd);
}