Write a C program to read a data from file and display


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

 Live Demo

#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

Updated on: 06-Mar-2021

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements