【发布时间】:2015-02-12 01:47:49
【问题描述】:
我需要使用 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 打印正常。我做错了什么还是这是包?
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 );
使用这段代码我仍然有同样的错误
帮帮我:))
【问题讨论】:
-
您的 C++ 代码看起来很像 C。如果您将 C++ 的类用于字符串、流、文件等,您可能不会遇到这个问题。也没有任何你一定会遇到的问题。
-
不需要在字符串末尾加上
\0,编译器会自动添加。 -
您正在混合使用行缓冲和非行缓冲 I/O。
-
问题不在 '\0' 中。我可以使用 c++ 打印到管道吗?保罗你能解释一下吗?)
-
\0评论与问题无关,我只是指出它是多余的。我不确定我是否了解您的问题的确切性质,除非buf太短,否则我看不出您的代码将如何产生不正确的输出。