簡體   English   中英

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

[英]Getting file size with lseek command in c

我被要求找到文件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); } 

但是我的文件大小為-1,我在哪里出錯

lseek文檔在線獲取

返回值
成功完成后,lseek()返回結果偏移量位置,從文件開頭開始以字節為單位。 發生錯誤時,將返回值(off_t)-1,並且將errno設置為指示錯誤。

因此,您必須檢查errno (如果lseek返回-1errno打印出來):

來自同一鏈接的可能錯誤列表:

錯誤

  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. 干凈地編譯
  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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM