Write a program that receives three arguments from the command line: week09_1 file1.txt file2.txt file3.txt
Your program should open files file1.txt and file2.txt for reading and to create
file file3.txt as follows:
The first line of file3.txt is the first line of file1.txt
The second line of file3.txt is the first line of file2.txt
The third line of file3.txt is the second line of file1.txt
The fourth line of file3.txt is the second line of file2.txt
...
When one input file reaches the EOF, the remaining lines in the other file
should be copied to the output file and the program terminates. Your
program should print appropriate error messages if fewer than 3 file names
are provided on the command line or if the files cannot be opened.
So as of right now i have been able to do what the prompt is asking me to do; however, when one file runs out of lines to print and then it only prints from the other file the printing is on the same line, i am wondering how i can make it start a new line when its only printing from 1 file.
Also i do not understand how i am suppose to implement in the command line arguments the way the prompt is asking.
#include <stdio.h>
char line1[256] = { };
char line2[256] = { };
char check;
int END = 0, END1 = 0, END2 = 0;
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("Error: Wrong amount of arguments\n");
return 0;
}
FILE *file1 = fopen("argv[1]", "r");
FILE *file2 = fopen("argv[2]", "r");
FILE *file3 = fopen("argv[3]", "w");
if (argv == NULL) {
printf("Error: file could not be opened.\n");
return 0;
}
while (END != 2) {
check = fgets(line1, 256, file1);
if (check != NULL) {
fprintf(file3, "%s", line1);
} else if (check == NULL) {
END1 = 1;
}
check = fgets(line2, 256, file2);
if (check != NULL) {
fprintf(file3, "%s", line2);
} else if (check == NULL) {
END2 = 1;
}
END = END1 + END2;
}
return 0;
}
main()
, check the return values offopen()
, andfclose()
your files when you're done with them. – Emmetargv[1]
,argv[2]
, andargv[3]
if they're there; in this case,argc
will be 4. You should validate (at least) how many arguments have been given, and exit with a usage message ifargc
is not exactly 4. – Emmetfgets
. Either that, or you need to use bigger line buffers. – user3386109char line[] = {};
etc) - I'm not sure it even compiles. 256 is a bit small, but not unreasonably so. You could use 4096 and ignore the issue, or use POSIXgetline()
and cease having to worry about line length for most purposes. – Jonathan Leffler