Reading Files Line by Line in C

fgets() reads a line from a text stream into a bounded buffer. It is a simple way to process text or CSV files line by line without reading past the array capacity.

The original Plus2net example uses a sample CSV file. You can still download the sample test.csv file.

Read and Display Every Line Top ↑

#include <stdio.h>

int main(void) {
    FILE *file = fopen("test.csv", "r");
    char line[128];

    if (file == NULL) {
        perror("test.csv");
        return 1;
    }

    while (fgets(line, sizeof line, file) != NULL) {
        fputs(line, stdout);
    }

    fclose(file);
    return 0;
}

Read Only the First Line Top ↑

Key change: use one if instead of a loop when only the first line is required.

if (fgets(line, sizeof line, file) != NULL) {
    fputs(line, stdout);
}

Do Not Use feof() as the Loop Condition Top ↑

A common mistake is to loop on !feof(file). End-of-file is reported only after an attempted read reaches the end. Prefer testing the read operation itself:

while (fgets(line, sizeof line, file) != NULL) {
    /* process line */
}

Handle File-Open Errors Top ↑

#include <stdio.h>

int main(void) {
    FILE *file = fopen("missing.txt", "r");

    if (file == NULL) {
        perror("missing.txt");
        return 1;
    }

    fclose(file);
    return 0;
}

Read Structured Values with fscanf() Top ↑

#include <stdio.h>

int main(void) {
    FILE *file = fopen("products.txt", "r");
    int id;
    double price;

    if (file == NULL) {
        perror("products.txt");
        return 1;
    }

    while (fscanf(file, "%d %lf", &id, &price) == 2) {
        printf("Product ID: %d, Price: %.2f\n", id, price);
    }

    fclose(file);
    return 0;
}

Related File Tutorials Top ↑





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer