0

ファイルからデータを読み取り、配列に保存したい。次に、この配列に新しいデータを挿入し、この新しいデータを同じファイルに保存して、既存のものを削除します。私のコードは完全に機能し、fopen パラメーターに 'r+' がある場合、必要なデータが得られますが、ファイルに再度書き込むと、ファイルに既にあるデータは削除されず、期待どおりに最後に追加されます。ただし、アクセス許可を「r+」ではなく「w+」に変更すると、コードは実行されますが、ファイルにデータが読み込まれたり書き込まれたりしません! なぜこれが当てはまるのか誰にも分かりますか?私のコードは以下の通りです。

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

2 に答える 2

1

ドキュメントによると、 w+ オプションを使用すると、「読み取りと書き込みのために新しいファイルを開くか作成します。既存のコンテンツがあれば破棄します。」ファイルの内容は破棄されるためData、 とHeaderは空です。

于 2013-10-16T21:27:17.897 に答える
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);
于 2013-10-16T21:34:03.173 に答える