

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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\n", 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 −
#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:\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) // read words from file{ printf("%s\n", 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
- Related Questions & Answers
- How to read complete text file line by line using Python?
- How to list one filename per output line in Linux?
- How to display all the MySQL tables in one line?
- How to display mean line per group in facetted graph using ggplot2 in R?
- How to word-wrap text in Tkinter Text?
- How to display multiple labels in one line with Python Tkinter?
- How to force Tkinter text widget to stay on one line?
- How to set Adapter to Auto Complete Text view?
- How to execute Python multi-line statements in the one-line at command-line?
- MySQL - How to count all rows per table in one query?
- C program to Replace a word in a text by another given word
- How to concatenate multiple C++ strings on one line?
- How can we implement line wrap and word wrap text inside a JTextArea in Java?
- How can we combine multiple print statements per line in Python?
- Converting digits to word format using switch case in C language
Advertisements