簡體   English   中英

如何檢查C中的文件是否為空?

[英]How do i check if a file is empty in C?

我正在將txtfile導入文件,如何檢查輸入文件是否為空白。

我已經檢查了它是否無法讀取輸入。 這是我到目前為止所擁有的:

#include<stdio.h>
#include<stdlib.h>

int main (int argc, char *argv[]){

// argv[1] will contain the file name input. 

FILE *file = fopen(argv[1], "r");

// need to make sure the file is not empty, error case. 

if (file == NULL){
    printf("error");
    exit(0);
}
 // if the file is empty, print an empty line.

int size = ftell(file); // see if file is empty (size 0)
if (size == 0){
    printf("\n");
}
printf("%d",size);

大小檢查顯然不起作用,因為我輸入了幾個數字,大小仍然為0。有什么建議嗎?

您可以使用sys/stat.h並調用st_size結構成員的值:

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

int main (int argc, char *argv[]) {
    if (argc != 2) {
        return EXIT_FAILURE;
    }
    const char *filename = argv[1];
    struct stat st;
    if (stat(filename, &st) != 0) {
        return EXIT_FAILURE;
    }
    fprintf(stdout, "file size: %zd\n", st.st_size);
    return EXIT_SUCCESS;
}

怎么樣閱讀第一行。 看看你得到什么字符?

調用ftell()不會告訴您文件的大小。 從手冊頁:

ftell()函數獲取stream指向的流的文件位置指示符的當前值。

也就是說,它告訴您文件中的當前位置...對於新打開的文件,該位置始終為0 您需要先seek到文件的末尾(請參閱fseek() )。

ftell會告訴您文件指針所處的位置 ,打開文件后,該位置始終為0。

您可以在打開前使用stat ,或使用fseek在文件中(或末尾)查找某個距離,然后使用ftell

或者您將檢查延遲到之后。 即,您嘗試閱讀需要閱讀的所有內容,然后驗證您是否成功。

更新 :說到支票,您不能保證

// argv[1] will contain the file name input. 

為此,您需要檢查argc至少為2(第一個參數是可執行文件名稱)。 否則,您的文件名可能為NULL fopen應該只返回NULL ,但是在其他情況下,您可能會發現自己正在查看核心轉儲。

暫無
暫無

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

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