lettura simple

Reading and Writing Binary Files in Octave

In this tutorial, I'll show you how to read and write binary files in Octave using practical examples.

Firstly, what is a binary file? It's a file where data is encoded in binary code as sequences of bytes. They're typically marked with the .bin extension. Binary files are different from text files, which only contain plain text.

How to write a binary file

To write a new binary file, use the fopen() function and indicate the write attribute (w).

>> MyFile=fopen("test4.bin", "w");

Then, write some numbers into the file using the fwrite() function for writing binary files.

The syntax [1:9] writes a sequence of numbers from 1 to 9.

>> fwrite(MyFile,[1:9]);

Finally, close the write file with the fclose() function.

>> fclose(MyFile)

You've now created a binary file in your PC's folder.

Note that if you write an alphanumeric string in a binary file, it will be recorded as a sequence of ASCII codes. For instance, if you write fwrite(MyFile,"test") in the file, the sequence 116 101 115 116 is written, where 116=t, 101=e, 115=s, 116=t.

How to read a binary file

To read the content of a binary file, open the file with the fopen() function and indicate the read attribute (r).

MyFile=fopen("test4.bin", "r");

Read the content of the file using the fread() function for reading binary files.

Then, store the data in the variable rec.

>> rec = fread(MyFile)

Finally, close the read file with the fclose() function.

>> fclose(MyFile)

Now, you can view the data of the binary file in the rec variable.

>> rec
rec = 1
2
3
4
5
6
7
8
9

By following these steps, you can read or write any binary file using Octave.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin