-1

Edit: I simplified the original code.

The code is:

#include <stdio.h>
#include <unistd.h>

int     main(void)
{

    printf("printf1\n");
    write(1, "1 should be after printf\n", 25);

    printf("printf2\n");
    write(1, "2 should be after printf\n", 25);

    return 0;
}

Unexpected result on Ideone:

1 should be after printf
2 should be after printf
printf1
printf2

Expected result on cs50

printf1
1 should be after printf
printf2
2 should be after printf

Why is the output order different?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
rldyjb
  • 13
  • 2
  • 5
    you're not flushing the output after the printfs. when it gets flushed is OS dependent. See [this](/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin) – Tibrogargan Nov 08 '16 at 02:39
  • @Tibrogargan Thank you! You points me to the right direction. – rldyjb Nov 08 '16 at 04:38

1 Answers1

0

Here the printf waits for the buffer to be full while write does not do that. If you have a \n (new line character) at the end of your printf, Then it will call write as soon as it encounters the \n. Note that print also calls the write once the buffer is full. write will just outputs the given number of bytes into the terminal, Hence will be faster.

try your code as:

printf("i = %d\n", i);
ft_putstr("should be printed right after printf\n");
Darshan b
  • 157
  • 7
  • I tried the code with \n added to the printf, but the ft_putstr()'s contents still comes before printf()'s. You can see the result on http://ideone.com/zGacCM – rldyjb Nov 08 '16 at 05:58
  • I tried it on my local machine. It works as expected. Thanks! – rldyjb Nov 08 '16 at 06:28
  • printf("i = %d\n", i); fflush(stdout); ft_putstr("should be printed right after printf\n"); this will also work fine. just flush the buffer. – Darshan b Nov 08 '16 at 07:19