slip3
By: Anonymous5/19/2023115 views Public Note
#include
#include
#include
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;
}