在ecplise下使用cdt开发c程序,发现运行后终端没有输出,停止后会输出,
究其原因,就是因为输出内容停留在了输出缓冲区里,而没有及时输出到控制台界面,解决的方法很简单:在每个printf后加上fflush(stdout)即可,或者,像我一样,把printf用一个宏封装一下:
#define OUTPUT_STR(str) do{printf(str);fflush(stdout);}while(0)
但是如果你在printf里面不止一个参数呢,或者你就能保证你的团队没有人搞忘啊!所以今天我就来讲讲setbuf函数
函数名:
setvbuf
用 法:
int setvbuf(FILE *stream, char *buf, int type, unsigned size);
type : 期望缓冲区的类型:
_IOFBF(满缓冲):当缓冲区为空时,从流读入数据。或者当缓冲区满时,向流写入数 据。
_IOLBF(行缓冲):每次从流中读入一行数据或向流中写入一行数据。
_IONBF(无缓冲):直接从流中读入数据或直接向流中写入数据,而没有缓冲区。
size : 缓冲区内字节的数量。
注意:This function should be called once the file associated with the stream has already been opened but before any input or output operation has taken place.
意思是这个函数应该在打开流后,立即调用,在任何对该流做输入输出前
为了简便:你可以在main函数中最先就调用
////解决非vc6.0环境下的输出问题
setvbuf(stdout,NULL,_IONBF,0);
例子:
#include <stdio.h>
int main(void) {
FILE *input, *output;
char bufr[512];
input = fopen("file.in", "r+b");
output = fopen("file.out", "w");
/* set up input stream for minimal disk access,
using our own character buffer */
if (setvbuf(input, bufr, _IOFBF, 512) != 0)
printf("failed to set up buffer for input file\n");
else
printf("buffer set up for input file\n");
/* set up output stream for line buffering using space that
will be obtained through an indirect call to malloc */
if (setvbuf(output, NULL, _IOLBF, 132) != 0)
printf("failed to set up buffer for output file\n");
else
printf("buffer set up for output file\n");
/* perform file I/O here */
/* close files */
fclose(input);
fclose(output);
return 0;
}