How to change a specific line in a specific text file via matlab?
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Ivan Mich
am 2 Apr. 2020
Beantwortet: Walter Roberson
am 2 Apr. 2020
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
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 2 Apr. 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.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Low-Level File I/O finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!