How to read data from a file into cell array keeping indents undisturbed
Afficher commentaires plus anciens
I am trying to read a data from a file, modify it and write to a same file which I did using,
fid = fopen('file.ext','r');
fclose(fid);
lines = textscan(fid,'%s','Delimiter','\n');
...
fid = fopen('file.ext','w');
for row = 1:length(lines{1})
fprintf(fid,'%s\n',lines{1}{row});
end
fclose(fid);
But I could not reproduce the indents which were in the original file. So any suggestions to achieve this and make the above process easier?
Note: the file extension is not .txt but similar to text format. The data which I try to read has html tag elements and attributes.
I would also like to know whether there is any way to directly modify a file without reading it?
Thanks in advance!
2 commentaires
Jan
le 27 Sep 2020
If you close the file by fclose before running textscan, the code should fail with an error message.
Shankar Santhosh
le 28 Sep 2020
Réponse acceptée
Plus de réponses (1)
Rik
le 27 Sep 2020
3 votes
It will read a file to a cell array, one cell element per line, and it will preserve all leading and trailing spaces.
One of the advantages of a cell array is that you can trivially write out the modified file: fprintf(fid,'%s\n',txt{:}).
3 commentaires
Shankar Santhosh
le 28 Sep 2020
Rik
le 28 Sep 2020
This is compatible all the way back to Matlab 6.5, and it works on GNU Octave.
Shankar Santhosh
le 28 Sep 2020
Catégories
En savoir plus sur Text Data Preparation dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!