简体   繁体   English

您如何“刷新” write()系统调用?

[英]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. 我从用户处获取输入,然后使用read()和write()系统调用将其打印到标准输出。 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. 我仅为此使用低级I / O,因此不会实现C标准库。 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. 我问过的大多数人都说使用“ fflush”,但我认为这仅适用于stdio.h库,而我不会使用。 Thanks in advance for any advice or resources on the matter. 在此先感谢您提供任何建议或资源。

How do you “flush” the write() system call? 您如何“刷新” write()系统调用?

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. 我从用户处获取输入,然后使用read()write()系统调用将其打印到标准输出。 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. 十之八九你有第三个参数write错误。

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. 我问过的大多数人都说使用“ fflush”,但我认为这仅适用于stdio.h库,而我不会使用。

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 因此,一旦您读取了()内容,就应该调用此函数以擦除缓冲区

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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