2014-03-07 166 views
0

我得到「錯誤:無法檢查文件大小」。任何想法爲什麼?C:檢查文件大小

// Generate Content-Length                          
    int file_size; 
    int fd; 
    char clenbuf[BUFLEN]; 
    struct stat fs; 
    fd = open(filename, "r"); 
    if (fstat(fd, &fs) == -1) { 
    printf("Error: could not check file size\n"); 
    return; 
    } 
    file_size = fs.st_size; 
    sprintf(clenbuf, "Content-Length: %d", file_size); 
+0

你忘了檢查調用'open'是否成功與否。你也會在'fopen'和'open'之間感到困惑。嘗試啓用編譯器警告。 –

+1

在繼續使用之前,您是否考慮檢查'fopen()'調用的結果?它不只是魔法般地總是打開所有你在'filename'中傳遞它的東西。 –

回答

1

試試這樣說:

fd = open(filename, "r"); 
if (NULL == fd) { 
    printf("Could not open the file\n"); 
    exit(0); 
} 
if (fstat(fd, &fs) == -1) { 
    printf("Error: could not check file size\n"); 
    return; 
    } 
1

下包括失蹤:

#include <fcntl.h> 
+2

這會導致編譯時錯誤。但是,Q表示該程序運行,只是不如預期。 (我不會倒下,出於對Chuck Finley這個名字的尊重) – abelenky

+1

當我包含fcntl.h後,一切都很順利。我用-W -Wall編譯並沒有任何警告:) – chuckfinley