规定从TXT文件中读取的字符长度,到达指定长度就终止。
#include<stdio.h>
int main() {
FILE *fp;
char ch;
int i = 0;
//如果文件不存在,给出提示并退出
if ((fp = fopen("D:\\demo.txt", "rt")) == NULL) {
printf("Cannot open file, press any key to exit!");
getch();
exit(1);
}
// 假设第四次读取时就终止
//while ((ch = fgetc(fp)) != EOF && (i<5)) {
//每次读取一个字节,直到读取完毕
while ((ch = fgetc(fp)) != EOF ) {
putchar(ch); //读取一个字符就输出到屏幕上
i++;
}
putchar('\n'); //输出换行符
fclose(fp);
getch();
return 0;
}
本文介绍了一种使用C语言从TXT文件中读取字符的方法,通过设置读取长度来控制读取过程,确保在达到预设长度时停止读取。代码示例展示了如何打开文件,读取并打印字符,以及在完成操作后正确关闭文件。
787

被折叠的 条评论
为什么被折叠?



