常用操作
文件内容是否为空
#include <stdio.h>
int main() {
FILE *file;
int ch;
// 打开文件
file = fopen("test.txt", "r");
// 检查文件是否成功打开
if (file == NULL) {
printf("无法打开文件\n");
return 1;
}
// 尝试读取第一个字符
ch = fgetc(file);
// 检查是否达到了文件结尾(EOF),如果是则文件为空
if (ch == EOF) {
printf("文件为空\n");
} else {
printf("文件不为空,内容如下:\n");
// 回到文件开头,以便读取整个文件内容
ungetc(ch, file);
// 读取并打印文件内容
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
}
// 关闭文件
fclose(file);
return 0;
}