Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 321
user149100 Avatar asked Apr 23 '10 03:04

user149100


People also ask

How do you write an integer in Fwrite?

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.

How do you write an int file?

To write an integer to a file, you just have to open a file in write mode, convert the int to a string with str(), and use the write() function. If you want to add an integer to an existing file and append to the file, then you need to open the file in append mode.

What's the difference between fprintf and fwrite?

fprintf writes a string. fwrite writes bytes. So in your first case, you're writing the bytes that represent an integer to the file; if its value is "4", the four bytes will be in the non-printable ASCII range, so you won't see them in a text editor.


1 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 function extern?

like image 162
tylerl Avatar answered Sep 20 '22 12:09

tylerl