读取和写入文件matlab

时间:2013-10-16 21:05:33

标签: file matlab file-io

我想从文件中读取数据并将其保存到数组中。然后将一些新数据插入此数组,然后将此新数据保存回同一文件中,删除已存在的数据。当我在fopen参数中有'r +'时,我的代码完美地工作,给我所需的数据,但是当我再次写入文件时,它不会删除文件中已有的数据,只是按预期将其附加到结尾。但是当我将权限更改为'w +'而不是'r +'时,我的代码会运行,但不会读入数据或写入文件!任何人都知道为什么会这样吗?我的代码如下所示。

N = 1021;
b = [0;0;0;0;0];
% Opens file specified by user.
fid = fopen('testing','w+'); 

% Read header data
Header = fread(fid, 140);
% Move to start of data

fseek(fid,140,'bof');

% Read from end of config header to end of file and save it in an array 
% called data
Data = fread(fid,inf);

Data=reshape(Data,N,[]);
b=repmat(b,[1 size(Data,2)]);
r=[b ; Data];
r=r(:);
r = [Header;r];
% write new values into file
fwrite(fid,r);

fclose(fid);

% Opens file specified by user.
fid = fopen('test'); 
All = fread(fid,inf);

fclose(fid); 

2 个答案:

答案 0 :(得分:1)

根据文档,w +选项允许您“打开或创建新文件进行读写。如果有的话,丢弃现有内容。”该文件的内容将被丢弃,因此DataHeader为空。

答案 1 :(得分:0)

您需要在写入之前设置文件句柄的位置指示器。使用frewind(fid),您可以将其设置为文件的开头,否则文件将被写入/附加到当前位置。

N = 1021;
b = [0;0;0;0;0];
% Opens file specified by user.
fid = fopen('testing','r+'); 

% Read header data
Header = fread(fid, 140);
% Move to start of data

fseek(fid,140,'bof');

% Read from end of config header to end of file and save it in an array 
% called data
Data = fread(fid,inf);

Data=reshape(Data,N,[]);
b=repmat(b,[1 size(Data,2)]);
r=[b ; Data];
r=r(:);
r = [Header;r];
% write new values into file
frewind(fid);
fwrite(fid,r);

fclose(fid);

% Opens file specified by user.
fid = fopen('test'); 
All = fread(fid,inf);

fclose(fid);