Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a C program to read a data from file and display
In C programming, reading data from a file and displaying it is a fundamental file handling operation. This involves opening a file in read mode, reading its contents character by character, and formatting the output for better readability.
Syntax
FILE *fopen(const char *filename, const char *mode); int getc(FILE *stream); int fclose(FILE *stream);
File Opening Modes
Write mode ("w"):
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 and current content will be stored.
Read mode ("r"):
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.
Example: Reading and Displaying File Data in Tabular Form
The following program creates a file with comma-separated values and displays them in tabular format by replacing commas with tabs −
Note: Since this program involves file operations that require user input, it uses predefined data instead of interactive input for online compilation.
#include <stdio.h>
#include <stdlib.h>
int main() {
char ch;
FILE *fp;
/* Writing data to file */
fp = fopen("std1.txt", "w");
if (fp == NULL) {
printf("Error opening file for writing!
");
return 1;
}
/* Writing sample data to file */
fprintf(fp, "Name,Item,Price\nBhanu,1,23.4\nPriya,2,45.6
");
fclose(fp);
/* Reading data from file */
fp = fopen("std1.txt", "r");
if (fp == NULL) {
printf("Error opening file for reading!
");
return 1;
}
printf("Data from file in tabular format:
");
while ((ch = getc(fp)) != EOF) {
if (ch == ',')
printf("\t\t");
else
printf("%c", ch);
}
fclose(fp);
return 0;
}
Data from file in tabular format: Name Item Price Bhanu 1 23.4 Priya 2 45.6
How It Works
The program uses the following logic to display data in tabular form −
while ((ch = getc(fp)) != EOF) {
if (ch == ',')
printf("\t\t");
else
printf("%c", ch);
}
-
getc()reads one character at a time from the file - When a comma is encountered, it prints tab spaces for column alignment
- Other characters are printed as they are
- The loop continues until End of File (EOF) is reached
Key Points
- Always check if
fopen()returns NULL to handle file opening errors - Use
fclose()to properly close files after operations - The
getc()function reads characters one by one until EOF - Tab characters (
\t) help align data in columns
Conclusion
Reading data from files in C involves opening the file in read mode, processing characters sequentially, and formatting output as needed. Proper error checking and file closure are essential for robust file operations.
