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
0 个评论
采纳的回答
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)
add_to_file_content(filename);
dbtype(filename)
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
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 Center 和 File Exchange 中查找有关 Low-Level File I/O 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!