C Read From a File

Suppose the file students.txt has this text.

Robin 85
Maria 92
John 78

Read line by line with fgets

#include <stdio.h>

int main(void) {
    FILE *fp = fopen("students.txt", "r");
    char line[100];

    if (fp == NULL) {
        printf("Cannot open the file\n");
        return 1;
    }
    while (fgets(line, sizeof(line), fp) != NULL) {
        printf("%s", line);
    }
    fclose(fp);
    return 0;
}

Output:

Output of the above program is

Robin 85
Maria 92
John 78

fgets() returns NULL at the end of the file, so the loop stops there.

Read formatted data with fscanf

#include <stdio.h>

int main(void) {
    FILE *fp = fopen("students.txt", "r");
    char name[20];
    int marks, total = 0;

    if (fp == NULL) return 1;
    while (fscanf(fp, "%19s %d", name, &marks) == 2) {
        printf("%s scored %d\n", name, marks);
        total += marks;
    }
    fclose(fp);

    printf("Total = %d\n", total);
    return 0;
}

Output:

Output of the above program is

Robin scored 85
Maria scored 92
John scored 78
Total = 255

Read character by character with fgetc

#include <stdio.h>

int main(void) {
    FILE *fp = fopen("students.txt", "r");
    int ch, lines = 0;

    if (fp == NULL) return 1;
    while ((ch = fgetc(fp)) != EOF) {
        if (ch == '\n') lines++;
    }
    fclose(fp);

    printf("Lines = %d\n", lines);
    return 0;
}

Output:

Output of the above program is

Lines = 3

Store the result of fgetc() in an int, not in a char, because EOF is a special int value.

Note: Do not use while (!feof(fp)) as the loop condition. It runs one more time than needed. Check the return value of the read function instead, like above.

Next: C Command Line Arguments.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.