fopen file, read number with fscanf, then write back to same file with fprintf
Afficher commentaires plus anciens
I would like to open a txt file which has the number 200 in it, read it into MATLAB, add 20, then write it back to the same .txt file so it now contains the number 220.
This does exactly what I want, I can run it once and have the number 220 in the text file.
fileID = fopen('myfile.txt','r');
tmpSales = fscanf(fileID,'%f');
fclose(fileID);
tmpSales = tmpSales+20
fileID = fopen('myfile.txt','w');
fprintf(fileID,'%.2f',tmpSales)
fclose(fileID);
I cannot figure out how to do this without two calls to fopen, I've tried the r+ flag such as follows:
fileID = fopen('myfile.txt','r+');
tmpSales = fscanf(fileID,'%f');
tmpSales = tmpSales+20;
fprintf(fileID,'%.2f',tmpSales)
fclose(fileID);
But it produces this result: 200220.00
Any way to do it with just 1 call to fopen?
Thanks
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Low-Level File I/O dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!