OneCompiler

slip3& slip17

140

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>

#define MAX_FILENAME_LENGTH 256

int main() {
DIR *dir;
struct dirent *entry;
FILE *output_file;

dir = opendir(".");
if (dir == NULL) {
    perror("Error opening directory");
    return 1;
}

output_file = fopen("merged.txt", "w");
if (output_file == NULL) {
    perror("Error creating merged.txt file");
    return 1;
}

while ((entry = readdir(dir)) != NULL) {
    if (entry->d_type == DT_REG && strstr(entry->d_name, ".txt") != NULL) {
        FILE *input_file = fopen(entry->d_name, "r");
        if (input_file == NULL) {
            perror("Error opening input file");
            continue;
        }

        char buffer[MAX_FILENAME_LENGTH];
        size_t bytesRead;
        while ((bytesRead = fread(buffer, 1, sizeof(buffer), input_file)) > 0) {
            fwrite(buffer, 1, bytesRead, output_file);
        }

        fclose(input_file);
    }
}
fclose(output_file);
closedir(dir);
int merged_fd = open("merged.txt", O_RDONLY);
if (merged_fd == -1) {
    perror("Error opening merged.txt file");
    return 1;
}

return merged_fd;

}