view file output while debugging

↘锁芯ラ 提交于 2020-01-06 14:38:11

问题


The problem with redirecting the output to a file in debug mode is that I can not view the content of file (size is zero) until the program finish. With this usages:

FILE *f;
f = fopen("log.txt", "w");
fprintf(f, "cycle =%d\n", c);

while I am debugging, I want to view the track "cycle =" in the file right after stepping out "fprintf" statement.

Is there any way to do that?


回答1:


You can try to put fflush(f); after fprintf() function call, which will make the data be written immediately.




回答2:


While I don't see it in C99, setlinebuf() is a function that has been available in any C I needed it in. Calling setlinebuf() before the first output to the file forces each line to go out immediately using "line buffering".

f = fopen("log.txt", "w");
if ( !f )
   oops();
if ( debugging_mode )
    setlinebuf( f );

No need for individual calls to fflush(), fsync(), etc.

Beware this slows down programs doing lots of output so reserving it for debugging mode can be important for performance of some programs.

If you don't have setlinebuf(), try the following, which is C99:

   setvbuf(f, (char *)NULL, _IOLBF, 0);



回答3:


Use fsync:

FILE *f;
f = fopen("log.txt", "w");
fprintf(f, "cycle =%d\n", c);
fsync(f);



回答4:


Adding fflush(f) after your call fprintf should ensure that the output is visible to other programs (although not necessarily written to disk).

If this is code that you can't or would rather not modify, and you're debugging with GDB, you can get the debugger to call fflush for you with call fflush(f).




回答5:


See if this helps - How to monitor log files in real-time?



来源:https://stackoverflow.com/questions/7145134/view-file-output-while-debugging

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!