2015-10-05 82 views
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),因为它是包含字符串的单元格数组的单元格。

我怎样才能克服这个问题,并正确追加新的数据?

回答

1

而不是使用textscan将文件复制到您的内存,然后将其写回内存,您可以使用fseek来设置您要继续写入的指针。只要在文件结束之前放置一个字符并继续写入即可。

fseek(fid, -1, 'eof'); 
+0

同意,这是一个更好的方法!但是,在测试'fseek(fId,-1,'eof')'时,新数据不会附加到'}'之前的所需位置,而是附加到文件末尾。这是真的,在这种情况下,我必须用'fId = fopen(fileName,'a +')'打开文件吗? –

+0

也许'-1'不正确,因为末尾有空白字符(换行符)。你可以尝试追回10个字符,然后用'A = fread(fid,10,'uint8 => char')读取最后的10个字符;'' – Daniel