我有一个垃圾邮件的二进制文件。我正在使用MATLAB来查找好东西的开头,并希望将文件的其余部分从例如位置1388复制到新文件中。我知道我可以通过十六进制轻松地将十六进制文件读入一个新文件,但是我循环浏览了很多大文件,我会经常这样做,所以我希望有人知道某种方式倾倒部分文件进入新文件?
答案 0 :(得分:2)
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
答案 1 :(得分:1)
我认为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