Problem with the code in C. I get these errors: Lab1.c: In function ‘main’: Lab1
ID: 3844056 • Letter: P
Question
Problem with the code in C.
I get these errors:
Lab1.c: In function ‘main’:
Lab1.c:27:17: error: ‘arg’ undeclared (first use in this function)
target = fopen(arg[2], "w");
^
Lab1.c:27:17: note: each undeclared identifier is reported only once for each function it appears in
I was wondering how to fix these errors.
---------------------------------------------------------------------------------------------------------------------------------
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int ch;
// file descriptors
FILE *source, *target;
if (argc < 3) {
printf("Usage: fcopy <source> <target> ");
exit(EXIT_FAILURE);
}
// open source file for read
source = fopen(argv[1], "i");
if (source == NULL) // Could not open file
{
printf("1. Press any key to exit.. ");
exit(EXIT_FAILURE);
}
// open target file for write
target = fopen(arg[2], "w");
if (target == NULL) // Could not open file
{
fclose(source);
print("2. Press any key to exit... ");
exit(EXIT_FAILURE);
}
//Read character at a time for source file until we reach end of file (EOF)
// and write it to the target file
while ((ch = fgetc(source) ) != EOF)
fputc(ch, target);
print("File copied sucessfully./n");
// Must close both the files.
fclose(source);
fclose(target);
return 0;
}
Explanation / Answer
1. It's argv[2] instead of arg[2]
2.use printf instead of print
/*Rectified code:*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int ch;
// file descriptors
FILE *source, *target;
if (argc < 3) {
printf("Usage: fcopy <source> <target> ");
exit(EXIT_FAILURE);
}
// open source file for read
source = fopen(argv[1], "i");
if (source == NULL) // Could not open file
{
printf("1. Press any key to exit.. ");
exit(EXIT_FAILURE);
}
// open target file for write
target = fopen(arg[2], "w");
if (target == NULL) // Could not open file
{
fclose(source);
print("2. Press any key to exit... ");
exit(EXIT_FAILURE);
}
//Read character at a time for source file until we reach end of file (EOF)
// and write it to the target file
while ((ch = fgetc(source) ) != EOF)
fputc(ch, target);
print("File copied sucessfully./n");
// Must close both the files.
fclose(source);
fclose(target);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.