一、read 函数介绍
read 函数在头文件“#include <unistd.h>”中。
函数原型为 ssize_t read(int fd,void *buf,size_t len)
参数 fd,使用 open 函数打开文件之后返回的句柄。
参数*buf,读出的数据保存的位置。
参数 len,每次最多读 len 个字节。
返回值为 ssize 类型,出错会返回-1,其它数值表示实际写入的字节数,返回值大于 0 小于 len 的数值都是正常的。
二、例程
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define MAX_BUF 1000
main()
{
int fd;
ssize_t fr;
char *path = "/bin/test";
char read_buf[MAX_BUF];
fd = open(path,O_RDWR|O_CREAT, 0777);
if(fd==-1) perror("open");
else printf("successful open!\n");
fr = read(fd, read_buf, MAX_BUF);
if(fr == -1) perror("read");
else printf("successful read\n");
close(fd);
printf("%s: %s\n",path,read_buf);
}
三、运行效果