Read Multiple Files in C: Complete Guide

In C language, you can use file pointers and loops to read data from multiple files. Here is a simple example code demonstrating how to read data from multiple files.

#include <stdio.h>

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

    // 文件名列表
    char *filenames[] = {"file1.txt", "file2.txt", "file3.txt"};

    for (int i = 0; i < 3; i++) {
        // 打开文件
        file = fopen(filenames[i], "r");

        if (file == NULL) {
            printf("无法打开文件 %s\n", filenames[i]);
            return 1;
        }

        printf("正在读取文件 %s\n", filenames[i]);

        // 读取文件数据
        while (fgets(data, sizeof(data), file) != NULL) {
            printf("%s", data);
        }

        // 关闭文件
        fclose(file);
    }

    return 0;
}

In the code above, a string array called filenames containing multiple file names is first defined. A loop structure is then used to iterate through each file name in the array. Within the loop, the file is opened, its data is read and output to the console, and finally the file is closed. This allows for sequentially reading data from multiple files.

bannerAds