2017-04-14 52 views
-2

我這是應該通過文件一些文本這個循環有什麼問題?在fprintf中MATLAB

fid = fopen('wave_propagation_var5_alpha1delta1.CPS_001', 'rt+') 
fprintf(fid, 'dsadsado') 
for i =1:383 

      currentline = fgetl(fid) 
      currentline = strtrim(currentline) 
      if strcmp(currentline, '$$SOLID_ANORMAL')==1 
       fprintf(fid, 'hello') 
      elseif strcmp(currentline, '$$SOLID_DELTANORMAL')==1 
       fprintf(fid, num2str(deltalist(i))) 
      else 
      end 
    i=i+1 
end 

線2似乎正確打印到文件中搜索並添加循環。但我不明白爲什麼第7行和第9行不行。當我調試if語句得到滿足並且代碼進入兩行並執行它們時。當我打開目標文件時,我不明白爲什麼沒有發生。

+0

您正試圖在同一時間從同一文件讀取和寫入...寫入與您正在讀取的文件不同的文件。 – Suever

回答

0

如@Suever所示,不可能同時讀取和寫入同一個文件。閱讀和寫作之間需要frewindfseek。這是我在下面選擇的解決方案。

不是打開一個新文件進行寫操作的建議卜@ Suever的回答,它執行以下操作:

1)讀取現有的文件

2)記得寫使用ftell

位置

3)快退文件

4)寫入到位置使用fseekfprintf記得:

fid = fopen('wave_propagation_var5_alpha1delta1.CPS_001', 'rt+') 
    while ~feof(fid) 
     currentline = fgetl(fid) 
     currentline = strtrim(currentline) 
     if strcmp(currentline, '$$SOLID_ANORMAL')==1 
      alphaline = ftell(fid) 
     elseif strcmp(currentline, '$$SOLID_DELTANORMAL')==1 
      deltaline = ftell(fid) 
     else 
     end 
    end 

    frewind(fid) 
    fseek(fid,alphaline,0) 
    fprintf(fid, 'hello') 
    frewind(fid) 
    fseek(fid,deltaline,0) 
    fprintf(fid,num2str(deltalist(i))) 

雖然@ Suever的回答是完全有效的和可以接受的,我更喜歡這種方式,因爲它充分利用了rt+權限讀取寫作。它繞過了創建另一個文件來寫入的需求,並簡單地使用已經存在的文件對其進行必要的更改。

2

在MATLAB中嘗試主動讀寫同一個文件是一個壞主意。您將改爲使用不同的文件輸出。

fin = fopen('wave_propagation_var5_alpha1delta1.CPS_001', 'rt+'); 
fout = fopen('wave_propagation_var5_alpha1delta1.CPS_001.out', 'w'); 

for i =1:383 
    currentline = fgetl(fin) 
    currentline = strtrim(currentline) 
    if strcmp(currentline, '$$SOLID_ANORMAL')==1 
     fprintf(fout, 'hello') 
    elseif strcmp(currentline, '$$SOLID_DELTANORMAL')==1 
     fprintf(fout, num2str(deltalist(i))) 
    end 

    % Print a newline every time to get correspondence 
    fprintf(fout, '\n') 
    i=i+1 
end 

fclose(fin) 
fclose(fout) 

% Replace the input file with the output file if you want 
movefile('wave_propagation_var5_alpha1delta1.CPS_001.out', ... 
     'wave_propagation_var5_alpha1delta1.CPS_001'); 
+0

是的,但是這將打印到輸出文件中的不同位置,而不是輸入文件中,是否正確?可以說'$$ SOLID_ANORMAL'出現的那一行在那裏,就像第200行。當它被if語句檢測到並且我打印到fout時,它將打印在fout中的當前位置,這與當前位置不同鰭。 – user32882

+0

此外,在那種情況下,爲什麼在Matlab文檔中它提供了一個讀取和寫入(r +)fopen選項?如果這是一個壞主意,爲什麼他們將它作爲權限之一?https://nl.mathworks.com/help/matlab/ref/fopen.html#inputarg_permission – user32882

+0

@ user32882然後每次都打印一個換行符。查看更新。 – Suever