Fclose() causes Segmentation Fault

cfclosefile-iofopensegmentation-fault

I've been trying simple file handling in C and I wanted to make sure that the file can be accessed tried using this

#include<stdio.h>

main()
{
    CheckFile();
}

int CheckFile()
{
    int checkfile=0;

    FILE *fp1;
    fp1 = fopen("users.sav","r");

    if(fp1==NULL)
    {
        fopen("users.sav","w");
        fclose(fp1);
    }   
    if(checkfile!=0)printf("\nERROR ACCESSING FILE!\nNow exiting program with exit code: %d\n",checkfile);exit(1);
    return 0;
}

then it displays

Segmentation fault (core dumped)

but it doesn't segfault if the file already exists beforehand (e.g. when i created it manually or when i run the program the second time)

Please help. I need this for our final project due in a week and I haven't gotten the hang of files and pointers yet.

I'm using "gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1"

P.s

I saw this in another question

There's no guarantee in your original code that the fopen is actually working, in which case it will return NULL and the fclose will not be defined behaviour.

So how exactly do I check if it worked?

Best Answer

That's normal, when you call fclose(fp1) when fp1 is NULL.

BTW

fopen("users.sav","w");

is useless because you don't assign the return value to a file pointer. That means the users.sav file will be opened for writing, but you will never be able to write anything in it .

Related Topic