- The modified line appears after the line intended to be modified.
- This makes the next line read using "fgetl" function non char array and the script unexpectedly terminates.
Use fprintf with fgetl
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Francesco
le 20 Sep 2023
Réponse apportée : VINAYAK LUHA
le 26 Sep 2023
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);
0 commentaires
Réponse acceptée
VINAYAK LUHA
le 26 Sep 2023
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-
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Startup and Shutdown dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!