开发者

view file output while debugging

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" st开发者_Go百科atement.

Is there any way to do that?


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);


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


Use fsync:

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


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).


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜