| << Prev | Beej's Guide to C | Next >> |
Write binary data to a file.
#include <stdio.h> size_t fwrite(const void *p, size_t size, size_t nmemb, FILE *stream);
This is the counterpart to the fread() function. It writes blocks of binary data to disk. For a description of what this means, see the entry for fread().
fwrite() returns the number of items successfully written, which should hopefully be nmemb that you passed in. It'll return zero on error.
// save 10 random numbers to a file
int main(void)
{
int i;
int r[10];
FILE *fp;
// populate the array with random numbers:
for(i = 0; i < 10; i++) {
r[i] = rand();
}
// save the random numbers (10 ints) to the file
fp = fopen("binaryfile.dat", "wb");
fwrite(r, sizeof(int), 10, fp); // write 10 ints
fclose(fp);
return 0;
}
| << Prev | Beej's Guide to C | Next >> |