05 14

Writing in binary

bin","wb"); if (!ptr_myfile) { printf("Unable to open file!"); return 1; } for ( counter=1; counter <= 10; counter++) { my_record.x= counter; fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile); } fclose(ptr_myfile); return 0; }

In this example we declare a structure rec with the members x,y and z of the type integer. In the main function we open (fopen) a file for writing (w). Then we check if the file is open, if not, an error message is displayed and we exit the program. In the “for loop” we fill the structure member x with a number. Then we write the record to the file. We do this ten times, thus creating ten records. After writing the ten records, we will close the file (don’t forget this).

So now we have written to a file, let’s read from the file we have just created. Take a look at the example:

#include<stdio.h> /* Our structure */ struct rec { int x,y,z; }; int main() { int counter; FILE *ptr_myfile; struct rec my_record; ptr_myfile=fopen("test.bin","rb"); if (!ptr_myfile) { printf("Unable to open file!

writing in binary Write data to binary file - MATLAB fwrite - MathWorks


  1. Firodexok

    2/2 left socialists. Writing on the political wall as early as 2015 with momentum taking over constituencies / forcing de-selections.

  2. Dakosamiviqaya

    If I were writing an ipv6 text book I would throw binary emoji jokes into the addresses.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>