Read m file with fgets / fgetl
3 次查看(过去 30 天)
显示 更早的评论
Hi,
I want to read a m file called 'File1.m' and write in the same time a 'File2.m'.
My code (simplified for example) is :
Fin = fopen('File1.m','r');
Fout = fopen('File2.m','w');
while feof(Fin) == 0
line = fgets(Fin);
if regexp(line,'text')
fprintf(Fout,' modified text ');
else
fprintf(Fout,line);
end
end
It works perfectly EXCEPT that fgets is not reading comments in File1 (comments indicated with '%').
Do you know a way to read them? It is actually important comments.
Thanks, Clément
采纳的回答
Stephen23
2016-4-19
编辑:Stephen23
2016-4-21
Solution Use fgetl and this:
fprintf(Fout,'%s\n',line);
Explanation there is a very large difference between these:
fprintf(fid,'%s\n',text) % correct
fprintf(fid,text) % what you are doing
because of how escaped characters get handled. Characters that need escaping include %, so when you provide it simply (as you are doing) it does not get interpreted as a simple character, but instead is a special active character. The first line shows the correct solution for your task, with a format string and your text as an argument. Read the fprintf docs for more info on this, or this excellent explanation:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!