How to read a line of content from a file in C language?

In C language, you can use the standard library function fgets() to read a line of file content. The specific steps are as follows:

  1. Open the file: use the standard library function fopen() to open the file to be read and return a file pointer.
  2. Read a line of content using the fgets() function: Use the fgets() function to read a line of content from an opened file and store the content in a character array.
  3. Process the content that is read: process or output the content that is read.
  4. Close file: Use the fclose() function to close the file.

Here is a sample code:

#include <stdio.h>

int main() {
    FILE *file;
    char line[100];

    file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    while (fgets(line, sizeof(line), file) != NULL) {
        printf("%s", line);
    }

    fclose(file);

    return 0;
}

In the above example, the program opens a file named “example.txt” and reads each line of the file using the fgets() function, then prints the content to the console. Finally, it closes the file.

bannerAds