1

Is it possible to alternate writing between binary and regular writes on the same file?

Would i just need to keep opening and closing the file like so?

struct node x;
FILE* fout;
fout = fopen("output.bin", "wb");
fwrite(&x, sizeof(struct node), 1, fout);
fclose(fout);
fout = fopen("output.bin", "a");
fprintf("&d", x.data);
TemporaryFix
  • 2,008
  • 3
  • 30
  • 54

1 Answers1

1

As far as mixing on POSIX systems: Both of these are buffered stdio routines within the same library, and on POSIX (UNIX/Linux/Solaris/BSD) OS there is no difference between binary and text mode, so you can indeed mix them.

Typically fprintf will trigger flushes after each newline so as long as you aren't mixing fprintf/fwrite with direct write() you should be fine.

Regarding Windows: fopen supports the "b" mode, and there is indeed a difference. If a file is open in text mode, fseek will be limited to the beginning or current file pointer. I don't pretend to know if there would be any pitfalls using fprintf() in binary mode so I recommend you to check previous SO threads if Windows is your concern.

Difference between files writen in binary and text mode

Normally if I need to mix in formatted output with binary I use sprintf() or some other in memory mechanism to write to a buffer first, and then bulk write (flush) the buffered data with fwrite().

Community
  • 1
  • 1
codenheim
  • 20,467
  • 1
  • 59
  • 80
  • There is also the `_setmode` function that is specific to Windows. That would allow you to switch between binary and text I/O. –  Oct 26 '14 at 03:39
  • I doubt that there are differences in buffering between `fprintf` and `fwrite`, I think that's soley related to the stream where these functions are applied to. – mafso Oct 26 '14 at 03:49