HOME HTML EDITOR C JAVA PHP

C Read Files: Retrieving Stored Data

To read a file in C, you must first open it in read mode ("r"). If the file does not exist, fopen() will return NULL, so checking the file pointer is even more critical when reading than it is when writing.

1. Primary Reading Functions

Depending on how your data is structured, you have three main ways to read text from a file:

2. Implementation Example: Reading a Full Line

Using fgets() is the professional standard for reading text files because it prevents buffer overflows by letting you set a character limit.

#include <stdio.h>

int main() {
    FILE *fptr;
    char content[100];

    // Open for reading
    fptr = fopen("data.txt", "r");

    if (fptr != NULL) {
        // Read content and store it in the 'content' array
        while(fgets(content, 100, fptr)) {
            printf("%s", content);
        }

        fclose(fptr);
    } else {
        printf("Not able to open the file.");
    }

    return 0;
}

3. The "End of File" (EOF) Concept

When reading a file, C needs to know when to stop. The constant EOF (End Of File) is a special value returned by reading functions when they reach the end of the data stream.

4. Reading Formatted Data

If your file contains structured data, like a list of ages or prices, fscanf() is the best tool for the job.

int age;
char name[20];
// Assuming file contains: John 25
fscanf(fptr, "%s %d", name, &age);

5. Comparison: Reading Methods

Function Best For... Stops At...
fgetc() Low-level parsing. Every single character.
fgets() Reading sentences/paragraphs. Newline (\n) or Buffer limit.
fscanf() Specific data types (int, float). Whitespace or Tab.
Pro Tip: When using fgets(), it actually includes the newline character (\n) from the file in your string if it finds one. You might need to manually remove it if you plan to compare that string with another using strcmp().