How to implement binary file output in the C language?
In C language, to output data in binary form to a file, you can use the fwrite() function. The prototype of the fwrite() function is as follows:
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
ptr is a pointer to the data to be written, size is the size of each data item in bytes, nmemb is the number of data items to be written, and stream is a pointer to the file to be written to.
Here is a simple example demonstrating how to output data to a file in binary format.
#include <stdio.h>
int main() {
FILE *fp;
int data[] = {1, 2, 3, 4, 5};
fp = fopen("output.bin", "wb");
if (fp == NULL) {
printf("Error opening file\n");
return 1;
}
fwrite(data, sizeof(int), 5, fp);
fclose(fp);
return 0;
}
In this example, we define an integer array called data, and then open a file named “output.bin” in binary write mode (“wb”). Next, we use the fwrite() function to write the data from the integer array data into the file in binary format. Finally, we close the file.
After running the program, the file “output.bin” will store the data from the integer array data in binary format.