用 C 语言程序解释文件结束 (EOF)
文件结尾 (EOF) 表示输入结尾。
输入文本后,如果按 CTRL+Z,文本会终止,即表示文件已到达结尾且没有内容可读。
算法
参考以下为 EOF 提供的算法。
Step 1: Open file in write mode. Step 2: Until character reaches end of the file, write each character in filepointer. Step 3: Close file. Step 4: Again open file in read mode. Step 5: Reading the character from file until fp equals to EOF. Step 5: Print character on console. Step 6: Close file.
示例
以下是文件结尾 (EOF) 的 C 语言程序 −
#include <stdio.h> int main(){ char ch; FILE *fp; fp=fopen("std1.txt","w"); //open the file in write mode printf("enter the text then press cntrl Z:
"); while((ch = getchar())!=EOF) //reading char by char until it equals to EOF{ i.e. when u press ctrlZ the while loop terminates putc(ch,fp); } fclose(fp); fp=fopen("std1.txt","r"); printf("text on the file:
"); while ((ch=getc(fp))!=EOF) //reading the character from file until fp equals to EOF{ putchar(ch); } fclose(fp); return 0; }
输出
执行上述程序后,将生成以下结果 −
enter the text then press cntrl Z: This is the EOF demonstration example if your text typing is over press cntrlZ ^Z text on the file: This is the EOF demonstration example if your text typing is over press cntrlZ
广告