0
我有一個文件,它是通過Matlab從矢量M
寫入二進制數據值。該文件中寫入Matlab的fwrite
形式function myGenFile(fName, M)
以下腳本myGenFile.m
:將數據附加到Matlab中的文件,刪除符號前
% open output file
fId = fopen(fName, 'W');
% start by writing some things to the file
fprintf(fId, '{DATA BITLENGTH:%d}', length(M));
fprintf(fId, '{DATA LIST-%d:#', ceil(length(M)/8) + 1);
% pad to full bytes
lenRest = mod(length(M), 8);
M = [M, zeros(1, 8 - lenRest)];
% reverse order in bytes
M = reshape(M, 8, ceil(length(M)/8));
MReversed = zeros(8, ceil(length(M)/8));
for i = 1:8
MReversed(i,:) = M(9-i,:);
end
MM = reshape(MReversed, 1, 8*len8);
fwrite(fId, MM, 'ubit1');
% write some ending of the file
fprintf(fId, '}');
fclose(fId);
現在我想寫一個文件myAppendFile.m
,其中附加一些值到現有的文件,並具有以下形式:function myAppendFile(newData, fName)
。要做到這一點,我將不得不刪除尾隨「}」:
fId = fopen(nameFile,'r');
oldData = textscan(fId, '%s', 'Delimiter', '\n');
% remove the last character of the file; aka the ending '}'
oldData{end}{end} = oldData{end}{end}(1:end-1);
的問題是現在想寫oldData
成(寫newData
應該是微不足道的文件的時候,因爲它也像二進制數據的矢量M
),因爲它是包含字符串的單元格數組的單元格。
我怎樣才能克服這個問題,並正確追加新的數據?
同意,這是一個更好的方法!但是,在測試'fseek(fId,-1,'eof')'時,新數據不會附加到'}'之前的所需位置,而是附加到文件末尾。這是真的,在這種情況下,我必須用'fId = fopen(fileName,'a +')'打開文件嗎? –
也許'-1'不正確,因爲末尾有空白字符(換行符)。你可以嘗試追回10個字符,然後用'A = fread(fid,10,'uint8 => char')讀取最後的10個字符;'' – Daniel