首先,以写入模式打开文件。稍后,输入文本,直到到达文件结尾(EOF),即按ctrlZ关闭文件。
同样,以读取模式打开。然后,从文件中读取单词,并在单独的行中打印每个单词,然后关闭文件。
我们实现的每行打印一个单词的逻辑如下-
while ((ch=getc(fp))!=EOF){
if(fp){
char word[100];
while(fscanf(fp,"%s",word)!=EOF) // 从文件中读取单词{
printf("%s\n", word); // 在单独的行上打印每个单词。
}
fclose(fp); // 关闭文件。
}
}
示例
以下是C程序,每行显示一个单词的全文-
#include
int main(){
char ch;
FILE *fp;
fp=fopen("file.txt","w"); //以写入模式打开文件
printf("enter the text then press cntrl Z:\n");
while((ch = getchar())!=EOF){
putc(ch,fp);
}
fclose(fp);
fp=fopen("file.txt","r");
printf("text on the file:\n");
while ((ch=getc(fp))!=EOF){
if(fp){
char word[100];
while(fscanf(fp,"%s",word)!=EOF) // 从文件中读取单词{
printf("%s\n", word); // 在单独的行上打印每个单词。
}
fclose(fp); // 关闭文件。
}Else{
printf("file doesnot exist");
// 然后告诉用户该文件不存在。
}
}
return 0;
}输出结果
执行以上程序后,将产生以下结果-
enter the text then press ctrl Z:
Hi Hello Welcome To My World
^Z
text on the file:
Hi
Hello
Welcome
To
My
World