How to loop through file content in C language?

In C programming language, a loop structure can be used to read the contents of a file. Here is an example code:

#include <stdio.h>

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

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

    // 逐字符读取文件内容
    while ((c = fgetc(file)) != EOF) {
        printf("%c", c);
    }

    // 关闭文件
    fclose(file);

    return 0;
}

In the example code above, the file is opened using the fopen function with the parameter “r” to indicate it is being opened in read-only mode. If the file is successfully opened, the fopen function will return a pointer to the file; otherwise, it will return NULL.

Next, utilize a while loop structure to read the file content character by character. The fgetc function reads one character at a time and assigns it to the variable c. When the function returns EOF, it indicates that the end of the file has been reached.

Finally, use the fclose function to close the file and make sure to release resources.

Please note that the above code is for reference only, and may need to be adapted according to specific requirements when actually used.

bannerAds