[英]Instant redirect program output to file without buffering from batch file
I have C
program where the messages are printed with printf
command. 我有C
程序,其中使用printf
命令打印消息。 From batch file I call my program with 从批处理文件中,我使用
call myProgram.exe parms > myFile.txt
I need that myFile
be updated every time (or almost every time) when myProgram
print a message. 我需要在myProgram
打印消息时每次(或几乎每次)更新myFile
。 Now, I cannot see anything in file until the program finish its execution, probably because some buffering. 现在,在程序完成执行之前,我看不到文件中的任何内容,可能是因为有一些缓冲。 Is this buffering problem from my C
program, from my batch file
or from operating system, and how can I resolve it? 这是我的C
程序, batch file
还是操作系统的缓冲问题,如何解决?
stdio.h
functions are buffering. stdio.h
函数正在缓冲。 See setvbuf . 参见setvbuf 。 The buffering may be operating system specific, and may change when redirecting (eg because internally isatty(3) could be used inside printf
etc...). 缓冲可能是特定于操作系统的,并且在重定向时可能会更改(例如,因为内部isatty(3)可以在printf
等内部使用)。
Notice that this buffering is actually useful, and generally speeds up output a lot. 请注意,此缓冲实际上是有用的,通常可以大大提高输出速度。
The simplest way is to call fflush(3) from time to time. 最简单的方法是不时调用fflush(3) 。 Otherwise call setvbuf
with _IOFBF
on stdout
. 否则,在stdout
上使用_IOFBF
调用setvbuf
。
Using setvbuf
near the start of the program is simpler. 在程序开始附近使用setvbuf
更简单。 However, calling fflush
at appropriate places might be more efficient (because using a larger buffer should be faster). 但是,在适当的地方调用fflush
可能会更有效(因为使用更大的缓冲区应该更快)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.