In: Computer Science
Take the following code and modify the if(args >= 3) statement to work with a dynamic amount of inputs.
Example: ./cat file1 file2 file3 file4 filen-1 filen should output a text file that concatenates the files file1 to filen into one file
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char ch;
if (argc ==1)
{
while((ch = fgetc(stdin)) != EOF)
fputc(ch, stdout);
}
if (argc == 2)
{
File *fp = fopen(argv[1], "r");
if (fp == NULL)
{
printf("File
doesn't exist\n");
return -1;
{
while ((ch = fgetc(fp)) != EOF)
putchar(ch);
}
//ADD ARRAY OF ARGS
if (argc >= 3)
{
// Open files to be merged
// Open file to store the result
//change to accept filen+1 files if (fp1 == NULL || fp2 == NULL
|| fp3 == NULL)
{
puts("Could not open
files");
exit(0);
}
//change to copy into filen+1
// Copy contents of first file
to filen+1.txt
while ((ch = fgetc(fp1)) != EOF)
fputc(ch, stdout);
// Copy contents of second file
to file3.txt
while ((ch = fgetc(fp2)) != EOF)
fputc(ch, stdout);
fclose(fp1);
fclose(fp2);
{
retrun 0;
}
That should be FILE, not File
Here is code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char ch;
if (argc == 1)
{
printf("Invalid inputs\n");
}
if (argc == 2)
{
File *fp = fopen(argv[1], "r");
if (fp == NULL)
{
printf("File
doesn't exist\n");
return -1;
{
while ((ch = fgetc(fp)) != EOF)
putchar(ch);
}
//ADD ARRAY OF ARGS
if (argc >= 3)
{
FILE *f2 = fopen(argv[argc - 1], "a+");
for (int i = 1; i < argc - 1; i++)
{
printf("\nOpened file %s\n", argv[i]);
FILE *fp = fopen(argv[i], "r");
if (fp == NULL)
{
printf("%s File doesn't exist\n", argv[i]);
}
else
{
while ((ch = fgetc(fp)) != EOF)
{
fprintf(f2, "%c", ch);
}
fprintf(f2, "\n");
}
fclose(fp);
}
fclose(f2);
}
return 0;
}
file1.txt:
at velit vivamus vel nulla eget eros elementum pellentesque
quisque porta volutpat erat quisque erat eros viverra eget
dictumst maecenas ut massa quis augue luctus tincidunt nulla mollis
molestie lorem quisque
nunc nisl duis bibendum felis sed interdum venenatis turpis enim
blandit
interdum mauris non ligula pellentesque ultrices phasellus id
sapien in sapien iaculis congue vivamus metus arcu adipiscing
pulvinar nulla pede ullamcorper augue a suscipit nulla elit ac
nulla sed vel enim sit
file2.txt:
sapien sociis natoque penatibus et magnis dis parturient montes
nascetur ridiculus mus etiam vel
arcu sed augue aliquam erat volutpat in congue etiam justo etiam
pretium iaculis justo in hac habitasse
eros viverra eget congue eget semper rutrum nulla nunc purus
phasellus in felis donec semper sapien a libero
nibh in quis justo maecenas rhoncus aliquam lacus morbi quis tortor
id nulla ultrices aliquet
dui vel nisl duis ac nibh fusce lacus purus aliquet at
Output:
file3.txt: