user2887210
user2887210

Reputation: 35

Reading and writing to a file matlab

I want to read data from a file and save it into an array. Then insert some new data into this array and then save this new data back into the same file deleting what is already there. My code works perfectly, giving me my required data, when I have 'r+' in the fopen parameters, however when I write to the file again it does not delete the data already in the file just appends it to the end as expected. However when I change the permissions to 'w+' instead of 'r+', my code runs but no data is read in or wrote to the file! Anyone know why this might be the case? My code is as seen below.

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); 

Upvotes: 0

Views: 193

Answers (2)

Daniel
Daniel

Reputation: 36720

You need to set the position indicator of the filehandle before writing. With frewind(fid) you can set it to the beginning of the file, otherwise the file is written / appended at the current position.

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);

Upvotes: 0

Molly
Molly

Reputation: 13610

According to the documentation, the w+ option allows you to "Open or create new file for reading and writing. Discard existing contents, if any." The contents of the file are discarded, so Data and Header are empty.

Upvotes: 1

Related Questions