fwrite - Write binary data to file

Syntax

count = fwrite(fid, A)
count = fwrite(fid, A, precision)
count = fwrite(fid, A, precision, skip)
count = fwrite(fid, A, precision, skip, machineformat)

Description

count = fwrite(fid, A) writes the elements of matrix A to the specified file. The data is written to the file in column order, and a count is kept of the number of elements written successfully.

fid is an integer file identifier obtained from fopen, or 1 for standard output or 2 for standard error.

count = fwrite(fid, A, precision) writes the elements of matrix A to the specified file, translating MATLAB® values to the specified precision.

precision controls the form and size of the result. See fread for a list of allowed precisions. If precision is not specified, MATLAB uses the default, which is 'uint8'. For 'bitN' or 'ubitN' precisions, fwrite sets all bits in A when the value is out of range. If the precision is 'char' or 'char*1', MATLAB writes characters using the encoding scheme associated with the file. See fopen for more information.

count = fwrite(fid, A, precision, skip) includes an optional skip argument that specifies the number of bytes to skip before each precision value is written. With the skip argument present, fwrite skips and writes one value, skips and writes another value, etc., until all of A is written. If precision is a bit format like 'bitN' or 'ubitN', skip is specified in bits. This is useful for inserting data into noncontiguous fields in fixed-length records.

count = fwrite(fid, A, precision, skip, machineformat) treats the data written as having a format given by machineformat. You can obtain the machineformat argument from the output of the fopen function. See fopen for possible values for machineformat.

Remarks

You cannot view or type the contents of the file you are writing with fwrite until you close the file with the fclose function.

Examples

Example 1

This example creates a 100-byte binary file containing the 25 elements of the 5-by-5 magic square, stored as 4-byte integers:

fid = fopen('magic5.bin', 'wb');
fwrite(fid, magic(5), 'integer*4')

Example 2

This example takes a string of Unicode® characters, str, which contains Japanese text, and writes the string into a file using the Shift-JIS character encoding scheme:

fid = fopen('japanese_out.txt', 'w', 'n', 'Shift_JIS');
fwrite(fid, str, 'char');
fclose(fid);

See Also

fclose, ferror, fopen, fprintf, fread, fscanf, fseek, ftell

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS