How to display the complete text one word per line in C language?


First, open the file in write mode. Later on, enter the text until it reaches the End Of File (EOF) i.e. press ctrlZ to close the file.

Again, open in reading mode. Then, read words from the file and print each word in a separate line and close the file.

The logic we implement to print one word per line is as follows −

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.    } }

Example

Following is the C program to display the complete text one word per line −

 Live Demo

#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; }

Output

When the above program is executed, it produces the following result −

enter the text then press ctrl Z:
Hi Hello Welcome To My World
^Z
text on the file:
Hi
Hello
Welcome
To
My
World

Updated on: 08-Mar-2021

911 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements