
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Read Data from File and Display in C
Problem
How to read a series of items that are present in a file and display the data in columns or tabular form using C Programming
Solution
Create a file in write mode and write some series of information in the file and close it again open and display the series of data in columns on the console.
Write mode of opening the file
FILE *fp; fp =fopen ("sample.txt", "w");
If the file does not exist, then a new file will be created.
If the file exists, then old content gets erased & current content will be stored.
Read mode of opening the file
FILE *fp fp =fopen ("sample.txt", "r");
If the file does not exist, then fopen function returns NULL value.
If the file exists, then data is read from the file successfully.
The logic used to display data on the console in tabular form is −
while ((ch=getc(fp))!=EOF){ if(ch == ',') printf("\t\t"); else printf("%c",ch); }
Program
#include <stdio.h> #include<ctype.h> #include<stdlib.h> int main(){ char ch; FILE *fp; fp=fopen("std1.txt","w"); printf("enter the text.press cntrl Z:
"); while((ch = getchar())!=EOF){ putc(ch,fp); } fclose(fp); fp=fopen("std1.txt","r"); printf("text on the file:
"); while ((ch=getc(fp))!=EOF){ if(ch == ',') printf("\t\t"); else printf("%c",ch); } fclose(fp); return 0; }
Output
enter the text.press cntrl Z: Name,Item,Price Bhanu,1,23.4 Priya,2,45.6 ^Z text on the file: Name Item Price Bhanu 1 23.4 Priya 2 45.6
Advertisements