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

 Accepted Answer

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 Comments

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?
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.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!