Last active
August 17, 2023 08:47
-
-
Save AbrahamAriel/37aaa571774c18ef64052c14868b4fb8 to your computer and use it in GitHub Desktop.
(2017) Lab 7, Assignment 1: "Write a program to read all txt files (that is files that ends with .txt) in the current directory and merge them all to one txt file and returns a file descriptor for the new file."
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <dirent.h> | |
#include <string.h> | |
int main(void) { | |
FILE *input, *output; // Two files, input and output | |
char ch; // ch is used to assign characters from input file which will then be copied into the output file | |
char *txt = ".txt"; // TXT file extension | |
struct dirent *de; | |
DIR *dr = opendir("."); // Open directory for reading | |
// If directory doesn't exist, quit | |
if(dr == NULL) { | |
printf("Can't open current directory."); | |
return 0; | |
} | |
// Loop until all files and folders are read/accessed | |
while((de = readdir(dr)) != NULL) { | |
char *filename = de->d_name; // Get the filename | |
char *ext = strrchr(filename, '.'); // Get the extension | |
if(!(!ext || ext == filename)){ // Compare extension | |
if(strcmp(ext, txt) == 0) { // If a text file, go on | |
output = fopen("output.txt", "a+"); // Open output.txt for appending, if doesn't exist, create it. | |
input = fopen(filename, "r"); // Open the input file ()'filename') for reading | |
while(1) { // Loop through the input file | |
ch = fgetc(input); // Get the current character | |
if(ch == EOF) break; // Stop if EOF is found | |
putc(ch, output); // Put current character from the input file into output.txt | |
} | |
fclose(input); // Close input file | |
fclose(output); // Close output file | |
} | |
} | |
} | |
closedir(dr); // Close directory | |
printf("Succesfully copied the contents of all .txt files into output.txt.\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment