c++ - printf 和 fprintf 的不同结果

标签 c++ unix printf

我需要打印“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/

相关文章:

c - printf 期间出现访问冲突错误

C 编程 - 整数值打印不正确

c++ - 在类中使用析构函数

c++ - 如何将 constexpr 值传递给采用 const 引用的 CUDA 设备端函数?

linux - 用于检查电话号码的函数内的 Unix KornShell 脚本 bool 值

linux - 如何解决 AIX tar 命令套接字错误?

c - 子进程中fork()后泄漏,为什么?

c - sprintf 导致未定义的行为

c++ - 类似于枚举的 using 声明?

c++ - 'this'指针是否参与虚函数多态行为