开发者

fwrite write an integer

I'm trying to write a word to a file using this function:

extern void write_int(FILE * out, int num) {
   fwrite(&num,sizeof(int),1, out);
   开发者_如何学运维if(ferror(out)){
      perror(__func__);
      exit(EXIT_FAILURE);
   }
}

But I get a segmentation fault whenever it tries to run the fwrite. I looked at the man page for fwrite(3) and I feel like I used it correctly, is there something I'm missing?


Try this instead:

void write_int(FILE * out, int num) {
   if (NULL==out) {
       fprintf(stderr, "I bet you saw THAT coming.\n");
       exit(EXIT_FAILURE);
   }
   fwrite(&num,sizeof(int),1, out);
   if(ferror(out)){
      perror(__func__);
      exit(EXIT_FAILURE);
   }
}

And why was your original function extern?


Is the file handle valid? Did you fopen() with "w"? fwrite() will segfault if it's not.

The function itself really does nothing, so it's obviously the fwrite call that's the problem. Examine the arguments.


out does not contain the address of the file, rather it contains the address of the file pointer your passing in main. This function prototype should be like:

extern void write_int(FILE * & out, int num);

In this way you are making a double pointer to the pointer in main which is then pointing to the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜