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 ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by