How to change a specific line in a specific text file via matlab?

9 vues (au cours des 30 derniers jours)
Hello,
I have a problem with a code.
Firts of all I am using command readfile in order to read my file. As a result its is showing a 400x1 cell. From this cell I would like to change
the content of a specific line (eg line 65). In line 65 there is "A 563". I would like to change this line to "B 50".
How could I make it?
I have read many examples but I did not understand what I should to
Thank you

Réponse acceptée

Walter Roberson
Walter Roberson le 2 Avr 2020
filename = 'AppropriateFile.txt';
outfilename = 'Revised_File.txt';
LineToChange = 65;
NewContent = 'B 50';
S = fileread(filename);
SS = regexp(S, '\r?\n', 'split');
SS{LineToChange} = NewContent;
fid = fopen(outfilename, 'w');
fprintf(fid, '%s\n', SS{:});
fclose(fid);
It is not usually recommended ot make the output file name the same as the input file name: if you do that and there is a problem with the change, you could end up with the content of the file destroyed but the revised content not written into place. For example if there were an error in the fprintf() line, then the fopen() line right before that would already have discarded the existing content of the file, but the hypothetical error in the fprintf() would prevent the new content from being written in, and so the original content would be gone but the new content would not be there.

Plus de réponses (0)

Catégories

En savoir plus sur Low-Level File I/O dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by