我需要使用linux函数ssize_t write(int fd, const void *buf, size_t count);
打印“word = n”(其中n在[0..10])中进行流式处理的函数。试图使用fprintf,但它给出了奇怪的结果:程序在约1%的调用“woword = n”中打印,并且length
例如“woword = 7”是7. Printf打印完好。我做错了什么,或者这是包?与printf和fprintf不同的结果
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");
}
}
EDITED:
我所理解的,我们有2个theorys: 1)混合printf和写 2)fprintf中使用 '\ 0' 和 '\ N'
int length = sprintf(buf, "word=%i", probability);
int result = write(id_result, buf, length);
write(id_result, "\n", 1);
用这段代码我仍然有同样的错误
aa帮我:))
你的C++代码看起来很像C.如果你使用C++的类来处理字符串,流,文件等,你可能不会遇到这个问题。也没有任何你会遇到的主要问题。 – Biffen 2015-02-11 17:19:34
不需要在字符串末尾放置'\ 0',编译器自动添加它。 – 2015-02-11 17:22:25
您正在混合行缓冲和非行缓冲I/O。 – 2015-02-11 17:25:55