Hojin Cho
Hojin Cho

Reputation: 486

Segmentation Fault when I fread a binary file

I am not that good at C, but I have never seen anything like this before.

I have a binary file, file.bin, which has one long integer followed by a lot of double real numbers. So I wrote following:

#include <stdio.h>

int main(void) {
    char filename[1000];
    sprintf(filename, "~/file.bin");
    FILE *fp;
    long i;
    double x;

    fp=fopen(filename,"rb");

    fread(&i,sizeof(long),1,fp);

    printf("%ld\n",i);

    for (i=0;i<20;i++){
        fread(&x,sizeof(double),1,fp);
        printf("%le\n",x);
    }

    fclose(fp);
    return 0;
}

Segmentation violation occurs at the fread(&i,sizeof(long),1,fp); I wrote similar codes before in this fashion and they all worked fine, but this is not.

Thanks, in advance, for your answers.

FYI, I am using gcc 3.4.6 on a linux server.

Upvotes: 1

Views: 847

Answers (1)

Sir Jo Black
Sir Jo Black

Reputation: 2096

Are you sure the file exists and fp is not NULL?!!!

I tried your code and, if the file exists, it runs also if the file contains no data.

I recommend you to insert a control after the file opening:

fp=fopen(filename,"rb");
if (fp==NULL) {
    perror("Error ");
    return errno;
}

If you use errno remember to include errno.h!

#include <errno.h>

This patch solves only the error due to the NULL assignement of fp, but shall be better you consider also the errors the fread() function returns if you read beyond the end (and other cases). See fread specifications: http://www.cplusplus.com/reference/cstdio/fread/

Upvotes: 1

Related Questions