We are interested in the implementation of a Unix/Linux system utility for the concatenation of a list of n text files. In order to do that we are going to consider the following syntax below where the concatenation of n text files are written in the output file all.txt or on the console if the output text file is not specified. In C
$./mycat file_1.txt file_2.txt . . . file_n.txt > all.txt
Attach your solution, named mycat.c, here
Following code can be used.
int cbd_merge_files(const char** filenames, int n, const char* final_filename) {
//opening files
FILE* fp = fopen(final_filename, "wb");
if (fp == NULL) return 1;
char buffer[4097];
//iterating over all the files to append
for (int i = 0; i < n; ++i) {
const char* fname = filenames[i];
FILE* fp_read = fopen(fname, "rb");
if (fp_read == NULL) return 1;
int n;
// appending the files.
while ((n = fread(buffer, sizeof(char), 4096, fp_read))) {
int k = fwrite(buffer, sizeof(char), n, fp);
if (!k) return 1;
}
fclose(fp_read);
}
fclose(fp);
return 0;
}
int main(int argc, const char** argv)
{
cbd_merge_files(argv+1, argc-1, "output.txt");
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.