了解系统级读写功能
Understanding System level read and write functions
由于我对STD iostream和STDIO的不满,我决定创建自己的IO库。这对我的教育很有好处。
但是我有一个小问题。Linux read()在终端文件描述符上操作时,直到新行才会返回。因此,如果我要求10个字节,即使我键入20个字节,也不会返回。更糟糕的是,这10个额外的字节未记录在我通过的缓冲区中。
那10个额外的字节怎么了?Linux是否具有用于读数的缓冲区?我可以访问此缓冲区而不是提供自己的?
因此,Linux终端的默认行为是线条缓冲的。像这样的答案可以适应一次读取一个字符(如果您想要的话)。
要回答有关获取其他10个字节的问题,如果您进行其他阅读,它将返回其余的字节。以下示例演示了多个顺序读取。如果您在提示符处输入10个以上的字符,则第二次读取将在不封锁10和最多返回19个字符的情况下进行。
#include <unistd.h>
#include <stdio.h>
int main(int argc, char** argv)
{
int read1Count = 0;
int read2Count = 0;
char pBuffer[20];
printf("Provide input: ");
// flush stdout because buffering...
fflush(NULL)
read1Count = read(1, pBuffer, 10);
// flush stdout because buffering...
fflush(NULL)
printf("Provide input: ");
read2Count = read(1, pBuffer + 10, 10);
printf("nRead 1: '");
if (read1Count < 0)
{
perror("Error on first read");
}
for (int i = 0; i < read1Count; i++)
{
printf("%c", pBuffer[i]);
}
printf("'nRead 2: '");
if (read2Count < 0)
{
perror("Error on second read");
}
for (int i = 0; i< read2Count; i++)
{
// We started the second read at pBuffer[10]
printf("%c", pBuffer[i + 10]);
}
printf("'n");
}
编译并运行此内容,我看到了这个
Provide input: 12345678910
Provide input:
Read 1: '1234567891'
Read 2: '0
'
相关文章:
- 用C++快速读写文件
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 在一个读写器队列中,我可以用volatile替换原子吗
- C++套接字对不读/写父/子
- 如何调试读写器锁的死锁?
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- Linux 挂载使用重新挂载以允许读写
- C++中读/写二进制文件
- 如何读/写或遍历 std::array 中的特定元素范围?
- 内存排序或读取-修改-写入操作,仅(读/写)内存顺序
- USB-HID 读/写(重叠)等待单个对象不返回C++
- 了解系统级读写功能
- 具有读写功能的 UNIX 管道系统可执行"ls -la"命令
- 具有并发读写功能的嵌入式数据库
- 如何制作具有同步数据读/写功能的多客户端服务器
- boost套接字读写功能是否线程安全
- ostream读/写功能
- XML数据绑定-可以自动完成读/写功能
- 如何重载具有读写功能的下标操作符