K
Keith Thompson
Greg Martin said:There's lots of ways to accomplish this. This would work. Whether it's
what you need is another matter.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
FILE* out;
char bytes[] = { '\0', '\0', '\0' };
int sz = sizeof (bytes) / sizeof (bytes[0]);
int nw;
if (argc < 2) {
return EXIT_FAILURE;
}
if ((out = fopen (argv[1], "a")) != NULL) {
nw = fwrite (bytes, sizeof (bytes[0]), sz, out);
if (nw != sz) {
perror ("fwrite");
}
fclose (out);
}
return 0;
}
fopen()'s mode "a" is *text* append mode:
append; open or create text file for writing at end-of-file
If you write characters other than printable characters, '\n', and
'\t' to a text stream, they won't necessarily appear when you read
them back; see N1370 7.21.2p2 for details.
If you're writing 0 bytes to a file, you (obviously, I think)
need to do it in binary mode, probably by passing "ab" as the mode
argument to fopen().
Even that's not guaranteed to work since a binary stream "may,
however, have an implementation-defined number of null characters
appended to the end of the stream" (N1370 7.21.2p3). This would
most likely apply to a system that tracks sizes of binary files
in blocks rather than bytes. It almost certainly wouldn't be a
concern for any system the OP is likely to be using.