Reputation:
I'm copying a source file source.txt
to another file destination.txt
. Both of these .txt file exist in directory before running the code & each file contain only a single sentence. But I'm seeing error: Segmentation fault
in terminal output. Here is the C code:
#include<stdio.h>
#include<stdlib.h>
int main(void) {
FILE* sptr = NULL;
FILE* dptr = NULL;
int ch = 0;
if((sptr = fopen("source.txt", "r")) == NULL) {
printf("Error in opening source file.\n");
exit(1);
}
if((sptr = fopen("destination.txt", "w")) == NULL) {
printf("Error in opening destination file.\n");
exit(1);
}
while((ch = fgetc(sptr)) != EOF)
fputc(ch, dptr);
fclose(sptr);
fclose(dptr);
return 0;
}
Upvotes: 0
Views: 534
Reputation: 16550
the following code:
FILE*
variablesEXIT_FAILURE
macro from stdlib.h
and now, the code
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE* sptr = NULL;
FILE* dptr = NULL;
int ch = 0;
if((sptr = fopen("source.txt", "r")) == NULL)
{
perror("fopen to read source.txt failed");
exit( EXIT_FAILURE );
}
if((dptr = fopen("destination.txt", "w")) == NULL)
{
perror("fopen to trucante/write destination.txt failed");
exit( EXIT_FAILURE);
}
while((ch = fgetc(sptr)) != EOF)
fputc(ch, dptr);
fclose(sptr);
fclose(dptr);
return 0;
}
initial conditions:
source.txt contains:
this is a sentence
destination.txt contains:
this will be overwritten
after running the program:
source.txt contains:
this is a sentence
destination.txt contains:
this is a sentence
Upvotes: 0
Reputation: 2022
You are writing to destination file like
fputc(ch, dptr);
Please note that dptr is null when above line is executed.
Hence segmentation fault.
Upvotes: 2
Reputation:
Looks like you've fallen for copy-and-paste-itis!
if((sptr = fopen("source.txt", "r")) == NULL) {
printf("Error in opening source file.\n");
exit(1);
}
if((sptr = fopen("destination.txt", "w")) == NULL) {
printf("Error in opening destination file.\n");
exit(1);
}
sptr
is repeated, so the file is only open for writing. Trying to read from it could cause the segmentation fault.
Also, why do you complicate your variable initialising? This could just be written as:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE* sptr = fopen("source.txt", "r");
FILE* dptr = fopen("destination.txt", "w");
int ch = 0;
if(sptr == NULL) {
printf("Error in opening source file.\n");
exit(1);
}
if(dptr == NULL) {
printf("Error in opening destination file.\n");
exit(1);
}
while((ch = fgetc(sptr)) != EOF)
fputc(ch, dptr);
fclose(sptr);
fclose(dptr);
return 0;
}
Upvotes: 2