Matlab中你不熟悉的---读写二进制数据
读写二进制数据在本例中显示的脚本文件创建了一个含有10000个随机数的数组,以只写方式打开一个自定义文件,用64位浮点数格式把这个数据写入磁盘,并关闭文件。程序打开所要读取的文件,并读取数组,得到一个100×100的数组。它用来说明二进制I/O操作。% Script file: binary_io.m%% Purpose:% To illustrate the use of binary i/o functions.%% Record of revisions:% Date Programmer Description of change% ==== ========== =====================% 12/19/98 S. J. Chapman Original code%% Define variables:% count --Number of values read / written% fid --File id% filename --File name% in_array --Input array% msg --Open error message% out_array --Output array% status --Operation status% Prompt for file namefilename = input('Enter file name: ','s');% Generate the data arrayout_array = randn(1,10000);% Open the output file for writing. = fopen(filename,'w');% Was the open successful?if fid > 0 % Write the output data. count =fwrite(fid,out_array,'float64'); % Tell user disp(); % Close the file status = fclose(fid);else % Output file open failed. Display message. disp(msg);end% Now try to recover the data. Open the% file for reading. = fopen(filename,'r');% Was the open successful?if fid > 0 % Read the input data. =fread(fid,,'float64'); % Tell user disp(); % Close the file status = fclose(fid);else % Input file open failed.Display message. disp(msg);end当这个程序运行时,结果如下>> binary_ioEnter file name: testfile10000 values written...10000 values read...在当前目录下,有一个80000字节的文件testfile被创建,这个文件之所以占80000个字节,是因为它含有10000个64位的值,每一个值占8个字节。% Script file: binary_io.m
%
% Purpose:
% To illustrate the use of binary i/o functions.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 12/19/98 S. J. Chapman Original code
%
% Define variables:
% count -- Number of values read / written
% fid -- File id
% filename -- File name
% in_array -- Input array
% msg -- Open error message
% out_array -- Output array
% status -- Operation status
% Prompt for file name
filename = input('Enter file name: ','s');
% Generate the data array
out_array = randn(1,10000);
% Open the output file for writing.
= fopen(filename,'w');
% Was the open successful?
if fid > 0
% Write the output data.
count = fwrite(fid,out_array,'float64');
% Tell user
disp();
% Close the file
status = fclose(fid);
else
% Output file open failed. Display message.
disp(msg);
end
% Now try to recover the data. Open the
% file for reading.
= fopen(filename,'r');
% Was the open successful?
if fid > 0
% Read the input data.
= fread(fid,,'float64');
% Tell user
disp();
% Close the file
status = fclose(fid);
else
% Input file open failed. Display message.
disp(msg);
end
附上代码
页:
[1]