我有兩個文本文件:FILE1.TXT & FILE2.TXTMATLAB:如何從一個文件複製內容到舊文件的特定位置
FILE1.TXT的內容:
Required contents of file;
Required contents of file;
Required contents of file;
Required contents of file;
Required contents of file;
My old contents(1);
My old contents(2);
My old contents(3);
My old contents(4);
Required contents of file;
Required contents of file;
Required contents of file;
Required contents of file;
內容FILE2.TXT的:
My new var(1);
My new var(2);
My new var(3);
My new var(4);
我有一個UPD ateFile.m功能:正試圖從FILE1.TXT新變種取代舊的含量分別
function updateFile(file)
% Read the new contents
fid = fopen('file2.txt', 'r');
c1 = onCleanup(@()fclose(fid));
newVars = textscan(fid,'%s','Delimiter','\n');
newVars = newVars{1};
% Save the testfile in to a cellaray variable
fid = fopen(file, 'r');
c2 = onCleanup(@()fclose(fid));
oldContent = textscan(fid,'%s','Delimiter','\n');
% Search for specific strings
oldContentFound = strfind(oldContent{1},'My old contents(1);');
oldContentRowNo = find(~cellfun('isempty',oldContentFound));
% Move the file position marker to the correct line
fid = fopen(file, 'r+');
c3 = onCleanup(@()fclose(fid));
for k=1:(oldContentRowNo-1)
fgetl(fid);
end
% Call fseek between read and write operations
fseek(fid, 0, 'cof');
for idx = 1:length(newVars)
fprintf(fid, [newVars{idx} '\n']);
end
end
我現在面臨的問題是,FILE1.TXT仍包含不需要一些舊的內容。任何幫助,將不勝感激。
謝謝
平滑... :)工作完全正常 – Spooferman 2015-02-06 18:10:06