fedden
fedden

Reputation: 319

different results with printf and fprintf

I need function that prints "word=n" (where n in [0..10]) to stream using linux function ssize_t write(int fd, const void *buf, size_t count);. Trying to use fprintf, but it's give strange results : program prints in ~1% of calls "woword=n", and length for example "woword=7" are 7. Printf print all right. I'm doing something wrong or this is the bag ?

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:

how I understand, we have 2 theorys : 1) mixing printf and write 2) using '\0' and '\n' in fprintf

int length = sprintf( buf, "word=%i", probability );
int result = write( id_result, buf, length );
write( id_result, "\n", 1 );

with this code I still have same errors

aa help me :))

Upvotes: 0

Views: 488

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308130

If you are interspersing calls to printf (or write) and fprintf(stderr, ...) the output won't necessarily come out in order. There is buffering going on, and the actual output probably won't switch at the end-of-line character.

Upvotes: 3

Related Questions