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() returns NULL before using the file pointer.
  • fgetc() returns EOF when 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.

Updated on: 2026-03-15T09:57:06+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements