gpt4 book ai didi

c - 增加标准输出缓冲区大小

转载 作者:太空狗 更新时间:2023-10-29 11:29:39 26 4
gpt4 key购买 nike

我正在运行一个启动进程的程序,然后该进程写入我的程序使用的标准输出。问题是,我需要的输出大约是 42000 字节。标准输出缓冲区大小似乎是 8192,我不希望它在达到 42000 之前刷新。有没有办法设置它?

我试过这个:

setvbuf ( stdout , NULL , _IOFBF , 50000 ); // ie set it to 50000 bytes

关于子进程的代码,但它似乎根本不起作用。有人有什么想法吗?

最佳答案

您需要为 setvbuf() 提供一个缓冲区才能工作。

static char buf[50000]; /* buf must survive until stdout is closed */
setvbuf ( stdout , buf , _IOFBF , sizeof(buf) );

来自man page :

int setvbuf(FILE *stream, char *buf, int mode , size_t size);
...
Except for unbuffered files, the buf argument should point to a buffer at least size bytes long; this buffer will be used instead of the current buffer. If the argument buf is NULL, only the mode is affected; a new buffer will be allocated on the next read or write operation.

这是一个示例程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[]) {
char msg[42000];
char buf[50000];

setvbuf(stdout, buf, _IOFBF, sizeof(buf));
memset(msg, 'a', sizeof(msg));
msg[sizeof(msg)-1] = '\0';
puts(msg);
exit(0);
}

在我的系统上,strace 输出显示单次写入 42000 字节。

关于c - 增加标准输出缓冲区大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com