C documentation V1 Help

Reading from a File

Reading from a file in C involves using various functions to access and process the contents of a file. This page provides a detailed overview of how to read data from a file in a C program.

1. Opening a File

  • Begin by opening the file using the fopen function.

    FILE *filePointer; filePointer = fopen("example.txt", "r");
  • Ensure the file is successfully opened before proceeding.

    if (filePointer == NULL) { // Handle error }

2. Reading Characters

  • Use the fgetc function to read characters from a file.

    char character; character = fgetc(filePointer);

3. Reading Strings

  • Use functions like fgets or fscanf to read strings from a file.

    char buffer[100]; fgets(buffer, sizeof(buffer), filePointer);
  • Alternatively, you can use fscanf to read formatted data.

    fscanf(filePointer, "%s", buffer);

4. Reading Lines

  • For reading entire lines, use fgets or getline functions.

    char line[100]; fgets(line, sizeof(line), filePointer);
  • getline is useful for dynamic memory allocation.

    char *line = NULL; size_t len = 0; getline(&line, &len, filePointer);

5. Reading Numbers

  • Use functions like fscanf to read numeric data.

    int number; fscanf(filePointer, "%d", &number);

6. End-of-File (EOF) Handling

  • Check for the end of the file using the feof function.

    while (!feof(filePointer)) { // Read data }
  • Alternatively, use the return value of file reading functions.

    if (fscanf(filePointer, "%s", buffer) == EOF) { // Handle end-of-file or read error }

7. Closing the File

  • Always close the file after reading operations using the fclose function.

    fclose(filePointer);

Reading from a file in C requires careful error handling and consideration of the data format. Whether reading characters, strings, lines, or numeric data, appropriate functions should be used based on the expected content.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

Last modified: 25 February 2024