Read in, edit, write out
1 view (last 30 days)
Show older comments
I am trying to read in a text file which contains text and not just values, edit various aspects of it with reference to an array of values, and then write as a new file. I'm wondering what the best way to do this is. Currently I am trying to read the file in with textread which gives me a cell, then I am editing strings in the cell but I am having issues writing what I have edited to a new file. As a basic example I would do this:
Read in file, 'greeting.txt', which contains:
Hello
I am XX years old
Nice to meet you
I would then reference the XX to an array, change it and write the new file. Any suggestions on how to do this effectively would be greatly appreciated.
0 Comments
Answers (1)
Bob Thompson
on 1 Mar 2018
For text files I usually read the file in with textread, and then run through for the lines I'm looking for using fgetl() which can be used to examine each line individually. I like to run this through a while loop since I don't know how long the file is, and I just look for specific strings to edit.
After that is done I print everything out using fprintf, when I have to use strings. I have admittedly not written out a large block of text before, but I would imagine if you put the line read, lined edit, and line print commands in a loop then you can read and write your files all within a loop. This is likely not the most efficient way.
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!