2017-02-25 93 views
0

我想在MATLAB中替換文本文件中的字符串。替換文本文件中的字符串

讀取指定線I所使用的代碼:

fid = fopen(file_name, 'r'); 
tt = textscan(fid, '%s', 1, 'delimiter', '\n', 'headerlines', i); 
ttt = str2num(tt{1}{1}); 

其中file_name是我的文件和ttt的名稱是一個單元陣列,包含在整數變換後的第i串。現在

例如,ttt = 1 2 3 4 5 6 7 8

,我想改變tttttt = 0 0 0 0 0 0 0 0 ,並在文件中的第i行寫入新ttt

有沒有人有想法來處理這個問題?

回答

0

一個可能的實現是

fid = fopen('input.txt', 'r+'); 
tt = textscan(fid, '%s', 1, 'delimiter', '\n', 'headerlines', 1); % scan the second line 
tt = tt{1}{1}; 
ttt = str2num(tt); %parse all the integers from the string 
ttt = ttt*0; %set all integers to zero 

fseek(fid, length(tt), 'bof'); %go back to the start of the parsed line 
format = repmat('%d ', 1, length(ttt)); 
format = format(1:end-1); %remove the trailing space 
fprintf(fid, format, ttt); %overwrite the text in the file 

fclose(fid); %close the file 

這將改變input.txt中來自:

your first line 
1 2 3 4 5 6 7 8 
5 5 5 5 5 5 5 5 

your first line 
0 0 0 0 0 0 0 0 
5 5 5 5 5 5 5 5 

請注意,這是唯一可能改寫現有字符文件。如果你想插入新的字符,你有兩個重寫整個文件,或至少從你想插入新字符的位置重寫。