fopen file, read number with fscanf, then write back to same file with fprintf
조회 수: 5 (최근 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!