Use fprintf with fgetl

조회 수: 1 (최근 30일)
Francesco
Francesco 2023년 9월 20일
답변: VINAYAK LUHA 2023년 9월 26일
Hi, I have a text file. I use the fgetl to read all the lines from a text file (screenshot). filename is the path where is the text file. Where i find lines with abb_sat ("PE02") in the begginning of the line, I want to substitue the values in the original file with x_sp3, y_sp3, z_sp3 and dc_sp3 (fprintf inside the while). With this script I can sobstitue these values (x_sp3, y_sp3, z_sp3, dc_sp3) in the next lines and not in that one where I find "PE02". How can I use fprintf to sobsitute these values in the correct lines?
abb_sat = "PE02";
filename = strcat('C:\multiGNSS_v3\mgnssPre\ephConv\',out_sp3_abb,'\',num2str(YR+2000),'\',out_sp3_abb,num2str(WN),num2str(DoW),est);
FID = fopen ( filename , 'r+');
line = fgetl(FID);
x_sp3 = -10000.666666;
y_sp3 = -10.666666;
z_sp3 = -1000.666666;
dc_sp3 = -0.666666;
while ischar(line)
if ~isempty(strfind(line, abb_sat ))
fprintf(FID,'%.5s %13.6f %13.6f %13.6f %13.6f\n', abb_sat, x_sp3, y_sp3, z_sp3, dc_sp3);
end
line = fgetl(FID);
end
fclose(FID);

채택된 답변

VINAYAK LUHA
VINAYAK LUHA 2023년 9월 26일
Hi Francesco,
My understanding is that you have a text file with some lines beginning with "PE02" and you want a workaround to modify this line in the original file using "fprintf" function.
There are two issues in the code you shared-
  1. The modified line appears after the line intended to be modified.
  2. This makes the next line read using "fgetl" function non char array and the script unexpectedly terminates.
Here's a workaround that involves writing into a temporary file first and substituting the content with the original file at the end.
abb_sat = "PE02";
filename = strcat('C:\multiGNSS_v3\mgnssPre\ephConv\', out_sp3_abb, '\', num2str(YR+2000), '\', out_sp3_abb, num2str(WN), num2str(DoW), est);
tempFilename = 'temp.txt';
FID = fopen(filename, 'r');
FID_temp = fopen(tempFilename, 'w');
line = fgetl(FID);
x_sp3 = -10000.666666;
y_sp3 = -10.666666;
z_sp3 = -1000.666666;
dc_sp3 = -0.666666;
while ischar(line)
if ~isempty(strfind(line, abb_sat))
fprintf(FID_temp, '%.5s %13.6f %13.6f %13.6f %13.6f\n', abb_sat, x_sp3, y_sp3, z_sp3, dc_sp3);
else
fprintf(FID_temp, '%s\n', line);
end
line = fgetl(FID);
end
fclose(FID);
fclose(FID_temp);
fclose('all');
movefile(tempFilename, filename);
Hope this helps !
Regards
Vinayak Luha

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by