首页 > 解决方案 > 文件空检查

问题描述

我做了一个函数来检查文本文件是否为空。我使用 fseek 和 ftell 进行检查,但问题是如果第一行是 '\n' 并且下一行是 EOF 那么 ftell 将返回 2 而不是 0 。我想检查文件是否真的为空,但我想不出是否有办法检查上述情况。请帮忙 。这是我的代码

void fileReader(FILE *file,char filePath[]){
char output[100];
file = fopen(filePath,"r");
printf("Content of file : ");
fseek(file, 0, SEEK_END); 
printf("%d",ftell(file));
if(ftell(file)==0){
    printf("\nthere is nothing here");
}
else{  
    do{
        printf("%s", output);  
    }while (fscanf(file, "%s", output) != EOF);
} 
fclose(file);
}

标签: c

解决方案


但问题是如果第一行是 '\n' 并且下一行是 EOF 那么 ftell 将返回 2 但不是 0

您不想知道文件是否为空,这意味着它的大小为 0,但如果文件包含其他内容,例如空格、制表符、换行符等,在这种情况下,大小是不够的。一种方法可以是:

#include <stdio.h>

int main(int argc, char ** argv)
{
  FILE * fp;

  if (argc != 2)
    fprintf(stderr, "Usage %s <file>\n", *argv);
  else if ((fp = fopen(argv[1], "r")) == NULL)
    perror("cannot read file");
  else {
    char c;

    switch (fscanf(fp, " %c", &c)) { /* note the space before % */
    case EOF:
      puts("empty or only spaces");
      break;
    case 1:
      puts("non empty");
      break;
    default:
      perror("cannot read file");
      break;
    }
    fclose(fp);
  }

  return 0;
}

在要求绕过空格fscanf(fp, " %c", &c)之前的空间中(空格、制表符、换行符...)%

编译和执行:

pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out /dev/null
empty or only spaces
pi@raspberrypi:/tmp $ echo > e
pi@raspberrypi:/tmp $ wc -c e
1 e
pi@raspberrypi:/tmp $ ./a.out e
empty or only spaces
pi@raspberrypi:/tmp $ echo "   " > e
pi@raspberrypi:/tmp $ echo "   " >> e
pi@raspberrypi:/tmp $ wc -c e
8 e
pi@raspberrypi:/tmp $ ./a.out e
empty or only spaces
pi@raspberrypi:/tmp $ echo "a" >> e
pi@raspberrypi:/tmp $ cat e


a
pi@raspberrypi:/tmp $ ./a.out e
non empty
pi@raspberrypi:/tmp $ 
pi@raspberrypi:/tmp $ chmod -r e
pi@raspberrypi:/tmp $ ./a.out e
cannot read file: Permission denied
pi@raspberrypi:/tmp $ ./a.out
Usage ./a.out <file>
pi@raspberrypi:/tmp $ 

推荐阅读