How to read characters from a txt file one by one in C language?

In C language, the fgetc function can be used to read characters from a txt file one by one. Here is an example code:

#include <stdio.h>

int main() {
    FILE *file;
    char c;

    // 打开文件
    file = fopen("input.txt", "r");
    if (file == NULL) {
        printf("无法打开文件。\n");
        return 1;
    }

    // 逐一读取字符直到文件结束
    while ((c = fgetc(file)) != EOF) {
        printf("%c", c); // 输出字符
    }

    // 关闭文件
    fclose(file);

    return 0;
}

The code above will open a file named input.txt, then read each character in the file and output it to the screen. The fgetc function in the while loop will read the next character in the file into the variable c, until it reaches the end of the file (reaches the EOF marker).

Please be aware that when using the fgetc function, you need to include the stdio.h header file and check if the file is successfully opened (i.e. file is not NULL) after opening it to prevent errors.

bannerAds