【发布时间】:2019-10-23 21:22:27
【问题描述】:
我正在尝试寻找一种更简单的方式来读取文本文件。我以前从未用 C 编程过,所以这对我来说是全新的。我的目标是能够运行我的程序并让它自动打印到屏幕上。我下面的内容有效,但我每次都必须输入文件。任何帮助将不胜感激。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, file_name[25];
FILE *fp;
printf("Enter name of a file you wish to see\n");
gets(file_name);
fp = fopen(file_name, "r"); // read mode
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
printf("The contents of %s file are:\n", file_name);
while((ch = fgetc(fp)) != EOF)
printf("%c", ch);
fclose(fp);
return 0;
}
这是输出:
Enter name of a file you wish to see
warning: this program uses gets(), which is unsafe.
Data.txt
The contents of Data.txt file are:
1
2
3
4
5
6
7
8
9
10
【问题讨论】:
-
旁白:
char ch应该是函数fgetc()返回的int ch。 -
如果要每次都打开同一个文件,使用
char file_name[] = "Data.txt"; -
使用
gets()这句话你学到了什么? -
...尤其是缓冲区这么小
file_name[25]; -
@JohnFore 我已经更新了您接受的答案,以确保完整性和后代。也许调查不同的选项将帮助您了解 C 允许您解决问题的多种方式。