fwrite write an integer

user149100 picture user149100 · Apr 23, 2010 · Viewed 34.8k times · Source

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?

Answer

tylerl picture tylerl · Apr 23, 2010

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?