Vasu Subbannavar
Vasu Subbannavar

Reputation: 111

How to read and write to a normal text file in C?

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

Answers (1)

M&#246;lp
M&#246;lp

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

Related Questions