我如何检查 C 中的文件是否为空?

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

我正在将一个 txt 文件导入到我的文件中,如何检查输入文件是否为空白。

我已经检查过它是否无法读取输入。这是我目前所拥有的:

#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。有什么建议吗?

尝试阅读第一行怎么样。 看看你得到了什么字符?

调用ftell()不会告诉你文件的大小。来自手册页:

The ftell() function obtains the current value of the file position indicator for the stream pointed to by stream.

也就是说,它告诉您当前在文件中的位置...对于新打开的文件,它始终是 0。您需要先 seek 到文件末尾(参见 fseek())。

ftell会告诉你文件指针所在的位置,当你打开文件后,这个位置总是0。

您可以在打开前使用stat,或者使用fseek在文件中(或末尾)寻找一段距离然后使用ftell

或者您将检查延迟到之后。即,您尝试阅读您需要阅读的任何内容,然后验证您是否成功。

更新:说到支票,你不能保证

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

为此,您需要检查 argc 是否至少为 2(第一个参数是可执行文件名称)。否则您的文件名可能是 NULLfopen 应该只是 return NULL,但在其他情况下,您可能会发现自己正在查看核心转储。

如果您使用的是常规文件(例如文本文件),您可以使用 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;
}