将数据附加到 Matlab 中的文件,在符号前删除
Appending data to a file in Matlab, removing before a symbol
我有一个文件,它是通过 Matlab 从具有二进制数据值的向量 M
写入的。此文件是用 Matlab 的 fwrite
在以下脚本 myGenFile.m
中编写的 function myGenFile(fName, M)
:
% 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
来设置要继续写入的指针,而不是使用 textscan
将文件复制到您的内存,然后将其写回。把它放在文件末尾前一个字符,然后继续写入。
fseek(fid, -1, 'eof');
我有一个文件,它是通过 Matlab 从具有二进制数据值的向量 M
写入的。此文件是用 Matlab 的 fwrite
在以下脚本 myGenFile.m
中编写的 function myGenFile(fName, M)
:
% 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
来设置要继续写入的指针,而不是使用 textscan
将文件复制到您的内存,然后将其写回。把它放在文件末尾前一个字符,然后继续写入。
fseek(fid, -1, 'eof');