|
名称: read()
头文件: #include <unistd.h>
原型: ssize_t read(int fd, void *buf, size_t count);
描述: read() 从文件描述符 fd 中读取 count 字节的数据并放入从 buf 开始的缓冲区中.如果 count 为零,
read()返回0,不执行其他任何操作。如果 count 大 于SSIZE_MAX,那么结果将不可预料。
参数: fd 文件描述符
buf 用来存放数据的目的缓冲区
count 要读取的字节数
返回值: -1 遇到错误
成功时返回读取到的字节数(为零表示读到文件描述符).
这里有个问题,就是最终读到的数据可能没有所要求的那么多。可能的原因是,文件中剩余的数据没有要求的那么多。比如,程序要求读 1000个字节的数据,而文件的长度却只有 500 个字节,那么程序也只能读到 500字节。当读到文件末尾,而还要再读的话,返回值就是0,因为已经没有数据可读了。
#include <unistd.h>
#include <stdlib.h>
int main()
{
char buffer[128];
int nread;
nread = read(0, buffer, 128); //读出来放进去
if (nread == -1)
write(2, "A read error has occurred\n", 26);
if ((write(1, buffer, nread)) != nread) //从放进去的地方取出来写到另外一个地方
write(2, "A write error has occurred\n", 27);
exit(0);
}
两种输入方式:
1、[root@localhost C]# echo hello world | ./read.exe hello world
2、[root@localhost C]# ./read.exe < test.txt
yes i am here
由程序代码及上看到,管道、重定向的输入都是“标准输入”。 |
|