adding a text in a file

I need to add in a text file(which is an xml file)a line text. I need to copy each line to the new file after reading the word 'here' I need to add a line then copy the rest of the text to the new one, Please I need an answer, Thank you

 채택된 답변

Ken Atwell
Ken Atwell 2012년 3월 8일

0 개 추천

I would first get this working without file I/O:
str = 'Add new text HERE and then the rest';
ins = strfind(str, 'HERE') + 4; % Add 4 to account for length of "HERE"
str = [str(1:ins) '(like so) ' str(ins+1:end) ];
str
You're working with XML, so make sure the new string you are creating remains valid XML.
Then, use fopen, fread, and fclose to:
  1. Open the original file
  2. Read all of its contents
  3. Close the original
Then do the text insertion, and then create a new file with fopen, fwrite, and fclose.

댓글 수: 2

suzie rodnick
suzie rodnick 2012년 3월 8일
Thank you very much for your response:
I'm very new with matlab: Do I need to read the whole content of the file at ones or line by line?
Ken Atwell
Ken Atwell 2012년 3월 8일
MATLAB can go either way -- I read the whole file, but fgetl can go line by line (in a "for" loop, presumably). Remember that line breaks in XML are not required (they are there for human readability), so I would hesitate to write code that demands they be there.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by