replace a textline in file

6 views (last 30 days)
Vipin Mohan
Vipin Mohan on 18 Sep 2014
Answered: Guillaume on 18 Sep 2014
Hi all,
I want to replace a text line with a user input (float number).
Text file :
OMT_INRT = { 0.0; 0.0; 0.0 }
PROJ_EPSI = { 0.0; 0.0; 0.0 }
NIT_RAXI = {0;0;0.0000006566506 }
NIT_VAXI = { 0; 0; 0 }
NIT_RANG = { 0; 0; 0 }
I want to replace '0.0000006566506' with a user input '0.003'. But what I am getting is ,
'NIT_RAXI = {0;0;0.003}006566506 }'
My program :
form = 'NIT_RAXI = {0;0;%0.3f}';
inp=input('replacement \n\n') ;
fid = fopen(filename,'r+');
for p=1:(n-1)
fgetl(fid);
end
fseek(fid, 0, 'cof');
f{i}= fprintf(fid, form,inp);
fclose(fid);
Note: all the terms in the left side of '=' are unique terms only. So i find the position of 'NIT_RAXI' ,.. that is at 'n', here n=3... and stored the whole file in f{i}
Thanks in advance

Accepted Answer

Guillaume
Guillaume on 18 Sep 2014
Your problem is that you only write as many characters as you need for your replacement and leave the rest of the line (and the file) alone, thus anything that was longer than your replacement remains.
You have two options:
  • if it's acceptable replace the rest of the line with spaces. You need to calculate the difference between the length of the original line and your replacement to know how many spaces to write.
  • shift all the content after your replacement to remove the extra characters. You can only do that if you write to a different file though (maybe a temporary file that you then use to replace the original file).
A few other things:
  • fseek(fid, 0, 'cof') does nothing. It says move 0 bytes from where you are now, that is don't move.
  • You're not storing the whole file or any part of it in f{i}, just how many bytes you've written.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!