Fwrite write integer

I am 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 error whenever it tries to run fwrite. I looked at the man page for fwrite (3) and I feel like I used it correctly, is there something I am missing?

+3
source share
3 answers

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 feature extern?

+5
source

What platform / compiler? Alignment issues can make a difference.

Can you write anything else to the file successfully? I suspect your file is not opening properly.

0
source

? fopen() "w"? fwrite() segfault, .

, , , fwrite, . .

0
source

Source: https://habr.com/ru/post/1742386/


All Articles