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
Selected Reading
Print contents of a file in C
In C, printing the contents of a file involves opening the file, reading its data character by character or line by line, and displaying it on the console. The fopen(), fgetc(), and fclose() functions are commonly used for this purpose.
Syntax
FILE *fopen(const char *filename, const char *mode); int fgetc(FILE *stream); int fclose(FILE *stream);
Method 1: Reading Character by Character
Let's say we have "new.txt" file with the following content −
0,hell!o 1,hello! 2,gfdtrhtrhrt 3,demo
Note: Create a file named "new.txt" in your working directory with the above content before running the program.
Here's an example to print the contents using character-by-character reading −
#include <stdio.h>
int main() {
FILE *f;
char s;
f = fopen("new.txt", "r");
if (f == NULL) {
printf("Error: Could not open file.<br>");
return 1;
}
while ((s = fgetc(f)) != EOF) {
printf("%c", s);
}
fclose(f);
return 0;
}
0,hell!o 1,hello! 2,gfdtrhtrhrt 3,demo
Method 2: Reading Line by Line
Alternatively, you can read and print the file content line by line using fgets() −
#include <stdio.h>
int main() {
FILE *f;
char line[256];
f = fopen("new.txt", "r");
if (f == NULL) {
printf("Error: Could not open file.<br>");
return 1;
}
while (fgets(line, sizeof(line), f) != NULL) {
printf("%s", line);
}
fclose(f);
return 0;
}
0,hell!o 1,hello! 2,gfdtrhtrhrt 3,demo
Key Points
- Always check if
fopen()returnsNULLbefore using the file pointer. -
fgetc()returnsEOFwhen end of file is reached. -
fgets()reads entire lines and includes the newline character. - Always call
fclose()to properly close the file and free resources.
Conclusion
Reading and printing file contents in C can be done character-by-character using fgetc() or line-by-line using fgets(). Both methods require proper file handling with error checking and resource cleanup.
Advertisements
