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?
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.
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.
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.
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
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With