Write data to binary file
fwrite(fileID,A) write the elements of array A as 8-bit unsigned integers to a binary file in column order. The binary file is indicated by the file identifier, fileID. Use fopen to open the file and obtain the fileID value. When you finish reading, close the file by calling fclose(fileID).
Open a file named nine.bin for writing. Specify write access using 'w' in the call to fopen.
fileID = fopen('nine.bin','w');
fopen returns a file identifier, fileID.
Write the integers from 1 to 9 as 8-bit unsigned integers.
Close the file.
Open a file named magic5.bin for writing.
fileID = fopen('magic5.bin','w');
Write the 25 elements of the 5-by-5 magic square. Use the precision argument, 'integer*4', to write 4-byte integers.
Close the file.
Write a binary file containing the elements of the 4-by-4 magic square, stored as double-precision floating-point numbers.
fileID = fopen('magic4.bin','w'); fwrite(fileID,magic(4),'double'); fclose(fileID);
Open the file, magic4.bin, with write-access that enables appending to the file. Specify the file-access type, 'a', in the call to fopen.
fileID = fopen('magic4.bin','a');
Append a 4-by-4 matrix of zeros to the file. Then, close the file.
Write random double-precision numbers to a file named myfile.bin for use on a big-endian system. Specify a machinefmt value of 'ieee-be' in the call to fwrite, to indicate big-endian byte ordering.
fileID = fopen('myfile.bin','w'); fwrite(fileID,rand(4),'double','ieee-be'); fclose(fileID);
File identifier, specified as an integer obtained from fopen, 1 for standard output (the screen), or 2 for standard error.
Data to write, specified as a numeric or character array.
Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char
Complex Number Support: Yes
Class and size in bits of the values to write, specified as one of the following strings in the Precision column.
|Value Type||Precision||Bits (Bytes)|
1 ≤ n ≤ 64
1 ≤ n ≤ 64
Depends on the encoding scheme associated with the file. Set encoding with fopen.
If you specify a precision of bitn or ubitn, then fwrite saturates for all values outside the range.
Number of bytes to skip before writing each value, specified as a scalar. If you specify a precision of bitn or ubitn, specify skip in bits.
Use the skip argument to insert data into noncontiguous fields in fixed-length records.
Order for writing bytes within the file, specified as one of the strings in the table that follows. For bitn and ubitn precisions, machinefmt specifies the order for writing bits within a byte, but the order for writing bytes remains your system byte ordering.
Your system byte ordering (default)
Big-endian ordering, 64-bit long data type
Little-endian ordering, 64-bit long data type
By default, all currently supported platforms use little-endian ordering for new files. Existing binary files can use either big-endian or little-endian ordering.