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

6 次查看(过去 30 天)
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

采纳的回答

Walter Roberson
Walter Roberson 2022-10-2
编辑:Walter Roberson 2022-10-2
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 个评论
Walter Roberson
Walter Roberson 2022-10-12
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."

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by