1

I am trying to read binary file using fread() but I keep getting a segmentation fault. I am sure the following code is correct:

FILE *fp = fopen("User/Admin/dataset.bin", "rb");
double *data = calloc(30 * 4, sizeof(double));
fread(data, sizeof(double), 30 * 4, fp);

Does anyone see an issue here! I really don't see it!!

4
  • 3
    you did not check to see if the open worked Commented Jun 30, 2017 at 17:29
  • 1
    There's probably a bug elsewhere in your code. Run your program though valgrind. If you're reading/writing someplace you shouldn't, it will tell you. Commented Jun 30, 2017 at 17:30
  • 2
    I'm guessing it's your file path, which is currently relative to where you execute this, since there's no forward-slash in front. Commented Jun 30, 2017 at 17:30
  • 4
    Despite your certainty, the fact that your program exhibits a segmentation fault proves that something is wrong with it. But perhaps the problem is somewhere else in it. Your chances of getting a useful answer will be much improved if you present a minimal reproducible example. Commented Jun 30, 2017 at 17:33

2 Answers 2

4

Have you checked the returns of fopen and calloc? You might be running into an issue with the file you are trying to read not being accessible (either not found or insufficient permissions) or your calloc could be failing to allocate memory.

You need to check the returned pointers to see if they are NULL like so:

FILE *fp = fopen("User/Admin/dataset.bin", "rb");
if(fp == NULL){
    perror("Failed to open file:\n");
    return; // or however you want to handle this
}
double *data = calloc(30 * 4, sizeof(double));
if(data == NULL){
     perror("Failed to allocate space for data pointer:\n");
     fclose(fp);
     return; // or however you want to handle this
}
fread(data, sizeof(double), 30 * 4, fp);

More than likely, the issue here is either insufficient privileges to open User/Admin/dataset.bin or the file path is incorrect.

Sign up to request clarification or add additional context in comments.

Comments

0

if code is right, and file can be opened successfully, may be the file size is smaller than 30*4*sizeof(double)

1 Comment

Wouldn't matter, you would just receive a short item count, e.g. man 3 fread "If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.