1、read函数的函数原型
#includessize_t read(int fd,void *buf,size_t count)
在函数原型中,ssize_t 指的是返回值;fd是要读取的文件的文件描述符;* buf是万能指针,一个任意类型的指针,议案是传进去一个地址;count是要读取的字节个数。同样地,在ubuntu界面输入:man 2 read
可以查看read函数的相关信息。该函数的作用是从文件描述符fd所指定的文件中读取“count”字节的大小到“buf”所指向的缓冲序列,它的返回值是实际读取到的字节数。
2、read函数应用实例
编写简单的read函数程序,使用gcc编译器编译。read函数程序如下所示:
#include#include #include #include #include #include int main(int argc,char *argv[]) { int fd; char buf[32]={0}; //char类型的buf,设置为32;给其做清零操作 ssize_t ret; //read函数的返回值是ssize_t类型的,现在给其定义一个返回值命名为ret fd = open("a.c",O_RDWR); //open"a.c文件",在之前open函数中已经创建了该文件 if(fd<0){ printf("open is errorn"); return -1; } printf("fd is %dn",fd); ret=read(fd,buf,32); //fd是通过open这个函数调用获得的;第二个参数是地址,写为buf; //第三个参数为要读取的字节数,这里选择写为32,与char buf[32]保持一致 //最后打印返回值 为何打印ret?因为如果读取成功的话会返回读取的字节数 //打印ret的值即可知道读取了多少字节 此处打开的是a.c 所以读取的时候会读取a.c里面的内容 //在ubuntu界面给a.c文件写入“hello readfunction!” if (ret<0){ printf("read is errorn"); return -2; } printf("buf is %sn",buf); printf("ret is %ldn",ret); close(fd); return 0; }
在ubuntu界面的运行结果命名为read为:
根据char buf[32]={0}与ret=read(fd,buf,32);测试是否最大读取字节为32?
将a.c文件的内容写为:hello readfunction!hellohellohellohellohello
查看运行结果,如下:(最大读取字节数为32)
3、说明
在man手册对于read函数的说明中提到:除去读取失败的情况,如果读取到文件的末尾,此时再读取时,返回值也会是0。
做一下测试,在刚才的c代码读取完成之后再加入一段读取操作。(将a.c文件的内容再回去“hello readfunction!”)
#include#include #include #include #include #include int main(int argc,char *argv[]) { int fd; char buf[32]={0}; //char类型的buf,设置为32;给其做清零操作 ssize_t ret; //read函数的返回值是ssize_t类型的,现在给其定义一个返回值命名为ret fd = open("a.c",O_RDWR); //open"a.c文件",在之前open函数中已经创建了该文件 if(fd<0){ printf("open is errorn"); return -1; } printf("fd is %dn",fd); ret=read(fd,buf,32); //fd是通过open这个函数调用获得的;第二个参数是地址,写为buf; //第三个参数为要读取的字节数,这里选择写为32,与char buf[32]保持一致 //最后打印返回值 为何打印ret?因为如果读取成功的话会返回读取的字节数 //打印ret的值即可知道读取了多少字节 此处打开的是a.c 所以读取的时候会读取a.c里面的内容 //在ubuntu界面给a.c文件写入“hello readfunction!” if (ret<0){ printf("read is errorn"); return -2; } printf("buf is %sn",buf); printf("ret is %ldn",ret); ret=read(fd,buf,32); if (ret<0){ printf("read is errorn"); return -2; } printf("buf is %sn",buf); printf("ret is %ldn",ret);//二次执行read读取 close(fd); return 0; }
在ubuntu界面的运行结果命名为read1,结果如下:
4.总结
在此次编写的代码中,read函数如果调用成功的话,它返回的是实际读到的字节数;它如果返回的是0,表示它已经读到了文件的末尾;如果返回的是-1,表示读取出错。



