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.
Asked
Active
Viewed 4,195 times
2 Answers
2
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()
andwrite()
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.

user207421
- 305,947
- 44
- 307
- 483
-
Yes, you were totally right. The third parameter to my write system call was incorrect. It's all fixed now! Thank you for all the clarifications! Have a good night. – HelpMe Oct 31 '17 at 06:47
-
`int` usually works, but to be completely correct, both `read()` and `write()` functions return `ssize_t`. – Andrew Henle Oct 31 '17 at 08:58
-1
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

Komal12
- 3,340
- 4
- 16
- 25

christian mali
- 9
- 1
-
1The OP mentions [system call](https://en.wikipedia.org/wiki/System_call)s, which on Linux are listed in [syscalls(2)](http://man7.org/linux/man-pages/man2/syscalls.2.html). The `read(2)` and `write(2)` system calls are not using C++ streams, it is the other way round. Read http://pages.cs.wisc.edu/~remzi/OSTEP/ for more – Basile Starynkevitch Oct 31 '17 at 07:23