【发布时间】:2013-12-09 16:04:17
【问题描述】:
我有一个二进制文件,开头有一些垃圾。我正在使用 MATLAB 来查找好东西的开头,并希望将文件的其余部分从例如位置 1388 复制到末尾到一个新文件中。我知道我可以轻松地将文件十六进制读取到一个新文件中,但是我正在循环浏览很多大文件,而且我会经常这样做,所以我希望有人知道一些转储部分文件的方法进入新文件?
【问题讨论】:
标签: matlab file-io binary copy
我有一个二进制文件,开头有一些垃圾。我正在使用 MATLAB 来查找好东西的开头,并希望将文件的其余部分从例如位置 1388 复制到末尾到一个新文件中。我知道我可以轻松地将文件十六进制读取到一个新文件中,但是我正在循环浏览很多大文件,而且我会经常这样做,所以我希望有人知道一些转储部分文件的方法进入新文件?
【问题讨论】:
标签: matlab file-io binary copy
fidin = fopen('input.txt','r');
fseek(fidin, 1388, 'bof');
bulksize = 8192;
count = bulksize;
fid = fopen('output.txt', 'a');
while (count >= bulksize) do
[A count] = fread(fidin, bulksize, '*uint8');
fwrite(fid, A);
end_while
fclose(fidin);
fclose(fid);
input.txt 输入文件 Output.txt 输出文件 1388 从文件开头的偏移量。
对于更大的文件,微调bulksize
【讨论】:
A。
fread(fidin, bulksize, '*uint8');
我认为 amald 的想法是正确的 (+1),但我的经验告诉我,他的实施无疑会在“现实来袭”时让你受伤:)
这是一个(IMO)更好的方法:
function yourFcn
% File names
inputFile = 'input.bin';
outputFile = 'output.bin';
% The computed offset (ideally, this is also done inside a try/catch)
offset = 1388;
% Amount of bytes per read
N = 8192;
% Open the files
fin = fopen(inputFile, 'r');
assert(fin > 0, 'yourFcn:ioError',...
'Error opening input file.');
fout = fopen(outputFile, 'w+');
if fout < 0
ME = MException('yourFcn:ioError',...
'Error opening output file.');
throw( closeFile(fin, inputFile, ME) );
end
% Set file pointer to computed offset
try
fseek(fin, offset, 'bof');
catch ME
ME = addCause(ME, MException('yourFcn:seekFailure',...
'Error applying offset to input file'));
closeBoth(ME);
end
% Read N bytes at a time, and dump them in the new file
try
while ~feof(fin)
assert(fwrite(fout,fread(fin,N)) == N, 'yourFcn:ioError',...
'Mismatch between bytes read and bytes written.');
end
catch ME
ME = addCause(ME, MException('yourFcn:writeError',...
'Error writing to output file'));
closeBoth(ME);
end
closeBoth();
% Safely close one of the files
function ME = closeFile(fid, fileName, ME)
try
fclose(fid);
catch ME2
errMsg = sprintf(['Error closing file ''%s''; ',...
'all file handles have been forcibly closed.'], fileName);
if isempty(ME_in)
ME = MException('yourFcn:closeError', errMsg);
else
ME.message = char(ME.message, errMsg);
end
ME = addCause(ME2, ME);
fclose('all');
end
end
% Safely close both files
function ME = closeBoth(ME_in)
if nargin == 0
ME_in = []; end
ME = closeFile(fin, inputFile, ME_in);
if isequal(ME,ME_in)
ME = closeFile(fout, outputFile, ME); end
if ~isempty(ME)
throw(ME); end
end
end
【讨论】: