replace a textline in file

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

采纳的回答

Guillaume
Guillaume 2014-9-18
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Text Data Preparation 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by