My program is supposed to merge two text files' lines together. For instance, if I have two files, one.txt
:
a b c d e f g h i j k l m
n o p q r s t u v w x y z
and two.txt
:
0 1 2 3 4
5 6 7 8 9
The output is:
a b c d e f g h i j k l m0 1 2 3 4
n o p q r s t u v w x y z5 6 7 8 9
However, I feel as though some of the conditions are redundant. However, I'm not sure how I can better design this.
// Program to merge lines from two files and output results
#include <stdio.h>
int main(int argc, char *argv[])
{
char *inName1 = argv[1], *inName2 = argv[2];
FILE *in1, *in2;
int c, d;
// Ensure correct usage
if (argc != 3)
{
fprintf(stderr, "Usage: ./merge <file1> <file2>\n");
return 1;
}
// Open input files and return if unable to open
if ((in1 = fopen(inName1, "r")) == NULL)
{
fprintf(stderr, "Can't open %s.\n", inName1);
return 2;
}
if ((in2 = fopen(inName2, "r")) == NULL)
{
fprintf(stderr, "Can't open %s.\n", inName2);
return 3;
}
// Take care of output
while ((c = getc(in1)) != EOF)
{
if (c != '\n')
putc(c, stdout);
else
{
while ((d = getc(in2)) != EOF)
{
if (d != '\n')
putc(d, stdout);
else
{
putc('\n', stdout);
break;
}
}
if (d == EOF)
{
while (c != EOF)
{
putc(c, stdout);
c = getc(in1);
}
}
}
}
if (c == EOF)
{
while ((d = getc(in2)) != EOF)
{
putc(d, stdout);
}
}
fclose(in1);
fclose(in2);
printf("\nProcess ended successfully.\n");
return 0;
}
paste -d ''
? \$\endgroup\$one.txt
andtwo.ext
exist like above, but 1 of them lacks a final'\n'
. Should output contain a final'\n'
? (IMO, it should) \$\endgroup\$