如何用 C 语言将完整的文本逐个单词一行显示?
首先,以写入模式打开文件。然后,输入文本,直到达到文件结尾 (EOF),即按下 ctrlZ 关闭文件。
再次以读取模式打开。然后,从文件中读取单词,并分别在一行中打印每个单词,然后关闭文件。
我们实现的用一行打印一个单词的逻辑如下 -
while ((ch=getc(fp))!=EOF){
if(fp){
char word[100];
while(fscanf(fp,"%s",word)!=EOF) // read words from file{
printf("%s
", word); // print each word on separate lines.
}
fclose(fp); // close file.
}
}示例
以下是显示完整文本,一行一个单词的 C 程序 -
#include<stdio.h>
int main(){
char ch;
FILE *fp;
fp=fopen("file.txt","w"); //open the file in write mode
printf("enter the text then press cntrl Z:
");
while((ch = getchar())!=EOF){
putc(ch,fp);
}
fclose(fp);
fp=fopen("file.txt","r");
printf("text on the file:
");
while ((ch=getc(fp))!=EOF){
if(fp){
char word[100];
while(fscanf(fp,"%s",word)!=EOF) // read words from file{
printf("%s
", word); // print each word on separate lines.
}
fclose(fp); // close file.
}
Else{
printf("file doesnot exist");
// then tells the user that the file does not 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP