fprintf can't make new line
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Gifari Zulkarnaen
le 22 Fév 2020
Modifié(e) : Stephen23
le 23 Fév 2020
I want to edit a line of a text file (tcl file actually). I tried with following code:
A = 5;
tcl = regexp(fileread('old_file.tcl'), '\n', 'split')';
tcl{3} = char(strcat("set A ",num2str(A),".0"));
fid = fopen('new_file.tcl','w');
fprintf(fid,'%s\n',tcl{:});
fclose(fid);
But it can't create new line after line 3. Instead, it create a character looks like small circle with black background, shown in figure below. I tried using fid==1 to check, it works fine in command window. How do I fix this? And if there is inefficiency in my code, suggestions are really appreciated. Thanks in advance.
0 commentaires
Réponse acceptée
Stephen23
le 22 Fév 2020
Modifié(e) : Stephen23
le 22 Fév 2020
Try opening the file in text mode, not binary mode:
A = 5;
tcl = regexp(fileread('old_file.tcl'), '[\n\r]+', 'split')';
tcl{3} = sprintf('set A %u.0',A);
fid = fopen('new_file.tcl','wt'); % text mode!
fprintf(fid,'%s\n',tcl{:});
fclose(fid);
6 commentaires
Gifari Zulkarnaen
le 23 Fév 2020
Modifié(e) : Gifari Zulkarnaen
le 23 Fév 2020
Stephen23
le 23 Fév 2020
Modifié(e) : Stephen23
le 23 Fév 2020
"...except that I need to delete last cell element so that it doesn't create additional empty last line in each iteration"
This is due to a trailing newline in the file, which when the text is split by regex creates an empty cell at the end of the array, which is thus printed as another line of text... itself with a newline at the end! I don't recommend just removing the last cell, because if the file does not end with a newline, then you will delete the last line of the file without any warning.
A more robust solution would be to check if the last cell is empty before deleting it, or to remove trailing whitespace when you import the file string:
str = deblank(fileread('Truss2.tcl')); % remove trailing whitespace
tcl = regexp(str,...)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Characters and Strings 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!