我需要打印“word=n”的函数(其中 n 在 [0..10] 中)以使用 linux 函数 ssize_t write(int fd, const void *buf, size_t count);
。尝试使用 fprintf,但它给出了奇怪的结果:程序在 ~1% 的调用中打印“woword=n”,而 length
例如“woword=7”是 7。Printf 打印正常。我做错了什么或者这是包?
if ((id_result = open( out , O_WRONLY)) <= 0) {
fprintf(stderr, "%s : %s\n", currentDateTime().c_str(), "could not open output\0");
ret = P_STREAMS_LOAD_ERROR;
}
void printProbability( int probability ){
char buf[50];
memset( buf, '\0', 50 );
int length = sprintf( buf, "word=%i\n\0", probability );
fprintf(stderr, "debug : word=%i len = %i\n\0", probability, length );
int result = write( id_result, buf, length );
if( result == -1){
fprintf(stderr, "%s : %s\n", currentDateTime().c_str(), "error \n");
}
}
编辑:
据我所知,我们有两种理论: 1) 混合 printf 和 write 2) 在 fprintf 中使用 '\0' 和 '\n'
int length = sprintf( buf, "word=%i", probability );
int result = write( id_result, buf, length );
write( id_result, "\n", 1 );
使用这段代码我仍然有同样的错误
aa 帮帮我 :))
最佳答案
如果您穿插调用 printf
(或 write
)和 fprintf(stderr, ...)
,输出不一定按顺序出来。正在进行缓冲,实际输出可能不会在行尾字符处切换。
关于c++ - printf 和 fprintf 的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28460415/