2015-02-06 15 views
1

我有兩個文本文件: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仍包含不需要一些舊的內容。任何幫助,將不勝感激。

謝謝

回答

1

您可以添加一些字符到該文件,但無法刪除一些。你必須用一個具有正確內容的新文件擦除你的文件。

這是你的功能的重寫,沒有工作:

function updateFile(file) 

% Read the new contents 
fid = fopen('file2.txt', 'r'); 
newVars = textscan(fid,'%s','Delimiter','\n'); 
fclose(fid); 
newVars = newVars{1}; 

% Read the old content 
fid = fopen(file, 'r'); 
f1 = textscan(fid, '%s', 'Delimiter', '\n'); 
fclose(fid); 
f1 = f1{1}; 

% Find pattern start line 
[~,k] = ismember('My old contents(1);', f1); 

% Replace pattern 
for i = 1:numel(newVars) 
    f1{k+i-1} = newVars{i}; 
end 

% Replace initial file 
fid = fopen(file, 'w'); 
cellfun(@(x) fprintf(fid, '%s\n', x), f1); 
fclose(fid); 

最佳,

+0

平滑... :)工作完全正常 – Spooferman 2015-02-06 18:10:06

0

文件訪問本質上是基於字節的。沒有在文件中間插入或刪除內容的事情。在大多數情況下,最簡單的方法是編輯內存中的內容,然後重寫整個文件。

在你的情況下,讀取輸入文件後,發現單元陣列中的開始和結束行,並簡單地用新的數據替換它們。然後再次打開文件進行正常寫入,然後輸出整個單元陣列。

相關問題