EN VI

why is the output not from top to bottom C?

2024-03-10 05:30:05
why is the output not from top to bottom C

my code looks 1:1 like this : you may disregard the ft_strlen function

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

int ft_strlen(char *c)
{
    int i = 0;
    while(c[i] != '\0')
    {
        i++;
    }

    return i;
}

int main() 
{
    char rockPaperScissores[] = "THIS IS rockPaperScissores^tm: ";
    int rps = ft_strlen(rockPaperScissores);
    
    printf("%d\n", rps);

    write(1, rockPaperScissores, rps);
    write(1, "LETS PLAY!!!\n", 13);

    for (int i = 51; i >= 49; i--)
    {
        write(1, &i , 1);
        write(1, "\n" , 1);
    }

    return 0;
}

and my OUTPUT looks like this :

THIS IS rockPaperScissores^tm: LETS PLAY!!!
3
2
1
31

my question now being...why is the "31" as last in my output when it should have been the first. Thanks for helping.

Solution:

The stdio functions use buffered io. Writes to the underlying file descriptor only happen when the buffer becomes full or when the program exits.[1] stdout is also flushed when a LF is encountered if it's connected to a terminal.

In your case, it appears that stdout wasn't connected to a terminal. Since the buffer never filled up, it wrote its output to the underling file descriptor on exit.


  1. Additionally, the buffer can be flushed explicitly using fflush. Also, it's possible to disable buffering for a handle. This is already done for stderr.
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login