Clear Filters
Clear Filters

How to append comment lines along with data while appending data from one .m file to another .m file

2 views (last 30 days)
I am appending data from one .m file to another .m file using fgets and fprintf but comments lines are not getting read with fgets. So I tried using fgetl, comments lines are getting read but not getting appended to other file using fprintf. Only data is appending but not comments. Please let me know if there is a way to append the comments along with data.

Accepted Answer

Walter Roberson
Walter Roberson on 31 Aug 2021
tnb = tempname();
tn1 = tnb + "1.m";
tn2 = tnb + "2.m";
[fid1, msg] = fopen(tn1, 'w');
if fid1 < 0; error('was not able to write to temporary file "%s" because "%s"', tn1, msg); end
cleanMe1 = onCleanup(@() delete(tn1));
fprintf(fid1, '%%comment 1\n%%comment 2\n1 2 3\n4 5 6\n');
fclose(fid1)
ans = 0
fprintf('contents of first file\n=====\n')
contents of first file =====
type(tn1)
%comment 1 %comment 2 1 2 3 4 5 6
fprintf('\n=====\n');
=====
[fid1, msg] = fopen(tn1, 'r');
if fid1 < 0; error('was not able to reopen temporary file "%s" for reading because "%s"', tn1, msg); end
[fid2, msg] = fopen(tn2, 'w');
if fid2 < 0; error('was not able to write to temporary file "%s" because "%s"', tn2, msg); end
cleanMe2 = onCleanup(@() delete(tn2));
while true
line_in = fgetl(fid1);
if ~ischar(line_in); break; end %end of file
fprintf(fid2, '%s\n', line_in);
end
fclose(fid1);
fclose(fid2);
fprintf('contents of second file\n=====\n')
contents of second file =====
type(tn2)
%comment 1 %comment 2 1 2 3 4 5 6
fprintf('\n=====\n');
=====
Remember that when you fprintf() and you put literal text into the format string, that you need to put two % for each % character that you want to output -- so for example where I wanted %comment to be output I had to write %%comment in the format string. This is because %comment would have be interpreted as the format string %c (write the next parameter as a character) followed by 'omment' . % is the format specification for fprintf.
That was when I used
fprintf(fid1, '%%comment 1\n%%comment 2\n1 2 3\n4 5 6\n');
to output. The better way would have been to use
fprintf(fid1, '%s\n%s\n%s\n%s\n', '%comment 1', '%comment 2', '1 2 3', '4 5 6');
Now the % in the %comment part, is data and not part of the format specification -- the format specification is the %s

More Answers (0)

Community Treasure Hunt

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

Start Hunting!