How to Read a File in C

In C programming language, you can use the following method to read file contents and output them:

  1. open a file
FILE *file = fopen("filename.txt", "r");
  1. Check if the file has been successfully opened: Use a file pointer to perform a null check to ensure that the file has been opened successfully. For example:
if (file == NULL) {
    printf("无法打开文件");
    return 1;
}
  1. read input from a file
  2. Reads a line from the specified file.
  3. use the printf function
  1. Read line by line using the fscanf() function.
char line[100];
while (fscanf(file, "%s", line) != EOF) {
    printf("%s\n", line);
}
  1. Read line by line using the fgets() function.
char line[100];
while (fgets(line, sizeof(line), file) != NULL) {
    printf("%s", line);
}
  1. Close the file.
fclose(file);

Complete code example:

#include <stdio.h>

int main() {
    FILE *file = fopen("filename.txt", "r");
    if (file == NULL) {
        printf("无法打开文件");
        return 1;
    }

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

    fclose(file);
    return 0;
}

Please ensure that the file exists and has the correct path before opening it. Additionally, the content read from the file will depend on its format and content type.

bannerAds