Read m file with fgets / fgetl

조회 수: 3 (최근 30일)
Clément P
Clément P 2016년 4월 19일
편집: Stephen23 2016년 4월 21일
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
  댓글 수: 3
Clément P
Clément P 2016년 4월 19일
편집: Clément P 2016년 4월 19일
I think that fgets takes into account the '\n', but fgetl does not. Maybe it is another symptom, but I don't understand why everything is write perfectly except comments. Or maybe it comes from sprintf?
edit : I checked, fgets reads all characters, including comments. I think it comes from fprintf , as the '%' is used to print variables. Do you have an idea how to overpass this?
Clément P
Clément P 2016년 4월 19일
Actually it works with fwrite ;)

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
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:
  댓글 수: 1
Clément P
Clément P 2016년 4월 20일
Thanks a lot for the explanations :D

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by