Replace one line in a text file with new line

11 views (last 30 days)
I am currently writing a code that opens a text file, and I want it to go to a line, delete what is at that line, and write in a line (using fprintf)
right now I have:
fid=fopen('sample.txt','r+');
format = '%4.2f, %4.2f, 1';
tline=fgetl(fid);
n=1;
while ischar(tline)
n=n+1
tline=fgetl(fid);
if n==148
fprintf(fid,format,pos(1, 1:2));
else
continue
end
fclose('all')
But it writes over text and pulls from other lines. I want each it to just erase what is on the line print to the one line and move on. Any ideas?

Accepted Answer

Walter Roberson
Walter Roberson on 18 Jun 2015
When you write into the middle of a text file like that, you are responsible for making the replacement exactly the same length as the original. It is not possible to put in shorter or longer lines in the middle of a text file without rewriting to the end of the file: filesystems have not supported the operation for the last 20 years or so.
Making a text file the same size or longer is possible in MATLAB (by writing the updated information) but making it shorter is not possible using only MATLAB calls; there is not a good reason for the inability to truncate.

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!