简体   繁体   中英

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.

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.

try this function:

eraseFunction()
{
    std::cin.clear();
    std::cin.ignore(std::cin.rdbuf()->in_avail());
}

so as soon as you read() something you should call this function to erase the buffer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM