Reputation: 111
I wrote this program by seeing a YouTube video.
In that, he used fopen_s
instead of fopen
and I have the latest gcc and g++
compiler installed, but they don't support fopen_s
. I am running into an error to close the file.
#include <stdio.h>
int main(){
FILE* file;
printf("loading file\n");
file = fopen("testFile.txt", "r+");
if (file == NULL){
printf("ERROR!!!");
fclose(file);
return 1;
}
printf("file pointer is loded\n");
fclose(file);
return 0;
}
This is the output
loading file
Segmentation fault (core dumped)
What's going wrong?
Upvotes: 0
Views: 126
Reputation: 162
The problem is, as described in the comments by Retired Ninja, you shouldn't close the file in the case file = NULL
because in that case nothing was opened. C will try to call the close function on a NULL pointer which will result in a seg fault.
To find out the reason, substitute your printf("ERROR!!");
for perror("error \n");
, which will give you the reason for the file not being succesfully opened.
What I suspect, in your case, is that you should give the directory of the file when calling fopen.
Upvotes: 1