Reputation: 1
I can't copy the contents of one file to another in C because there is a segmentation fault occurring and I don't know the cause.
I know it has something to do with the syntax of fgets or the way I am giving the size of the buffer.
char* argument = argv[2];
char buffer[argc + 1];
FILE *fp;
FILE *quiz_log;
fp = fopen(argument, "r+");
quiz_log = fopen("quiz.log", "a");
fgets(buffer, 80, fp);
memcpy("quiz.log", buffer, 80);
fclose(quiz_log);
fclose(fp);
Expected: Successful write to file "quiz.log"
Actual: Segmentation Fault: 11
Upvotes: 0
Views: 45
Reputation: 780974
argc
has nothing to do with the size of the file, it's the number of command line arguments. So there's no reason to use it as the size of the buffer.
Rather than try to read the file all at once, use a fixed-size buffer and read the file in a loop. Use fread()
rather than fgets()
, since that just reads one line.
You need to use fwrite()
to write to the output file, not memcpy()
.
#define BUFFER_SIZE 1000
char* argument = argv[2];
char buffer[BUFFER_SIZE];
FILE *fp;
FILE *quiz_log;
fp = fopen(argument, "r");
if (fp == NULL) {
printf("Unable to open input file\n");
exit(1);
}
quiz_log = fopen("quiz.log", "a");
if (quiz_log == NULL) {
printf("Unable to open quiz.log\n");
exit(1);
}
size_t n;
while ((n = fread(buffer, 1, BUFFER_SIZE, fp)) > 0) {
fwrite(buffer, 1, n, quiz_log);
}
fclose(quiz_log);
fclose(fp);
Upvotes: 3