1. 读二进制数据

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
function [ out ] = readBin( str, sz , precision)
%readBin read data generated by madagascar
%
% IN:
%    str: name of input data 
%    sz:  size of the input data
%    precision: precision of the input data
%
% OUT:
%    out: output
%
% Example:
%  cmp = readBin('cmp.rsf@',[n1,n2],'float');
%  imagesc(cmp);


fp = fopen(str,'rb');
out = fread(fp,precision);
out = reshape(out,sz);
fclose(fp);

end

2. 写二进制文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function  writeBin( str, d , precision)
    %writeBin write Binary format data
    %
    % IN:
    %    str: file name of output data 
    %    d:   the output data
    %    precision: precision of the output data
    %

    %
    % Example:
    %  writeBin('d.rsf@',d,'float');
    %  
    %

    if nargin == 2
        precision = 'float';
    end

    fp = fopen(str,'wb');
    fwrite(fp,d,precision);
    fclose(fp);
    
    end

3. 读入规则的数据文件

比如,一个命名为raw.txt的数据文件,存储了两列物理量,其内容是

1
2
3
4
5
10  1
20  2
30  3
40  4
50  5

可采用load函数来读入这样的数据

1
a = load('raw.txt');

4. 读入(不)规则的文本文件

4.1 规则文件

可以用textscan 函数来完成,该函数既可以读全是数值型的文本文件,也可以是字符型加数值型混合的文本文件,比如一个命名为mix.txt的文件,其内容如下

1
2
3
SC_XJI  1.2222 1234
SC_JJJ  1.0000 1111
SC_JKP  1.0001 1222

textscan读的代码如下:

1
2
3
fid = fopen('mix.txt');
C = textscan(fid,'%s %f %f');
fclose(fid);

4.2 不规则文件

对于不规则文件,比如bad.txt, 其内容如下:

1
2
3
SC_XJI  1.2222 1234
SC_JJJ  1.0000 1111 IAMROBOT
SC_JKP  1.0001 1222

比如,在上面的例子中第二行后面加了一个字符串,仍然可以用textscan来读这个文件,代码如下

1
2
3
fid = fopen('mix.txt');
C = textscan(fid,'%s %f %f %s'); % 注意这里多了一列 %s
fclose(fid);

4.3 带header的文本文件

对于带header的文本文件splitting_results.txt,比如:

1
2
3
4
5
baz si
10  1.0
20  1.2
30  0.8
40  0.9

这个文件由于第一行为头文件,所以不能简单用textscan来直接读取,正确的做法是在textscan中加一个跳过第一行的参数,具体如下:

1
2
3
4
fileID1 = fopen('splitting_results.txt');
final_data = textscan(fileID1,'%f %f',...
    'headerLines',1);
fclose(fileID1);

5. 写文本文件

写文本文件用fprintf函数即可

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
net = 'SC';
sta1 = 'XJI';
phi = 90;
dt = 0.2;
err_phi = 10;
err_dt = 0.02;
outfid = fopen('result.txt','w');
fprintf(outfid,'net_sta phi dt err_phi, err_dt\n');
fprintf(outfid,'%s %f %f %f %f\n', [net, '_', sta1], phi, dt, err_phi,err_dt);
fclose(outfid);

修订历史

  • 2021-08-09, 初稿;
  • 2021-10-21, 增加了有header信息的文本读取方式;