fopen file, read number with fscanf, then write back to same file with fprintf

7 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 2 Oct 2022
Edited: Walter Roberson on 2 Oct 2022
You need to rewind the file, or you need to fseek() to move the file pointer.
%prepare the initial file
filename = 'myfile.txt';
fileID = fopen(filename, 'w'); fprintf(fileID, '%g\n', 200); fclose(fileID);
%now do the work
add_to_file_content(filename);
dbtype(filename)
1 220.00
add_to_file_content(filename);
dbtype(filename)
1 240.00
function add_to_file_content(filename)
fileID = fopen(filename,'r+');
tmpSales = fscanf(fileID,'%f');
tmpSales = tmpSales+20;
frewind(fileID)
fprintf(fileID,'%.2f',tmpSales);
fclose(fileID);
end
  2 Comments
Walter Roberson
Walter Roberson on 12 Oct 2022
Note that the above code has a theoretical bug in the case where the result of adding 20 takes fewer printable characters than the input value. For example if there input were -13.00 then the computed value would be 7.00 which takes two fewer characters. When you frewind() or fseek() and write in new data, it does not somehow "shorten" the line it is on. The fprintf() operation there is not one of "replace line with this content", it is "write these characters starting at this location and stop when you run out of characters, even if you were in the middle of a line."

Sign in to comment.

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!