c++iolow-level-io

How do you "flush" the write() system call?


I am taking input from the user and then printing it to the standard output using read() and write() system calls. For some reason, it prints a few extra characters in addition to the regular output. The additional characters are from the user input, so they're not random. However, I am assuming that this may be due to the fact that the buffer is not cleared to take in new input. I searched many different things that would be appropriate in this scenario, but I am still confused. I am only using low-level I/O for this, so no C standard libraries will be implemented. The majority of people I've asked have said use "fflush", but I thought that would only be applicable with the stdio.h library, which I will not be using. Thanks in advance for any advice or resources on the matter.


Solution

  • How do you “flush” the write() system call?

    You don't. It's a system call. You don't have any application-side buffer to flush.

    I am taking input from the user and then printing it to the standard output using read() and write() system calls. For some reason, it prints a few extra characters in addition to the regular output.

    You have a bug in your code. It should look like this:

    int count;
    while ((count = read(inFD, buffer, sizeof buffer)) > 0)
    {
        write(outFD, buffer, count);
    }
    

    Ten to one you have the third parameter to write wrong.

    The majority of people I've asked have said use "fflush", but I thought that would only be applicable with the stdio.h library, which I will not be using.

    They are wrong and you are right.