c - 文件空检查
问题描述
我做了一个函数来检查文本文件是否为空。我使用 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);
}
解决方案
但问题是如果第一行是 '\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 $
推荐阅读
- scala - 从 Spray 重构为 Akka http
- spring - Spring测试:ApplicationContext配置类(spring data mongodb)
- c++ - 通过样式表将QTabWidget背景设置为透明但在VS2013中无用
- javascript - 使用 Create React App 创建对象时如何维护隐藏的 API 密钥
- asp.net-core - 使用 JWT 访问令牌的安全 API
- javascript - 来自默认导入的 Jest 模拟异步函数
- sql - SQL BigQuery 调用名称中包含多个点的列
- graph - 在 Neo4J 中获取特定类型的所有子图
- android - 布局大小超过 3500 行,提高活动加载速度
- asp.net-mvc - 如何使用 ASP.NET MVC 以浏览器的首选语言显示我的主页