赞
踩
参数说明
终端下输入man 2 read查看头文件与相关参数
man 2 read
- //头文件
- #include <unistd.h>
- //参数信息
- ssize_t read(int fd, void *buf, size_t count);
fd:需要写入文件的文件描述符
buf:缓冲区,用于存放读取的内容
count:要读取的字节大小
返回值
读取失败:返回值为-1;
读取成功:返回读取内容的字节数。(返回值不一定等于count,而是实际所读取的值)
代码示例
- #include <stdio.h>
- //以下是man手册查询的头文件
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- //strlen头文件
- #include <string.h>
- //malloc头文件
- #include <stdlib.h>
-
- int main()
- {
- int fd;//定义与open函数返回值相同的int型,便于接受返回值
- char *buf = "writeabcdefghijklmn";
- fd = open("./file1",O_RDONLY);//以只读的方式打开本目录下的file1文件
-
- if(fd == -1) //如果没打开 返回值为-1(肯定打不开,因为没创建)
- {
- printf("open file1 failed\n");//终端输出打开file1失败
- fd = open("./file2",O_CREAT|O_RDWR,0600);//如果不存在则创建以可读可写模式 权限为0600
- if(fd > 0)
- {
- printf("open file2 successful\n");//终端输出打开file2成功
- printf("fd = %d\n",fd);//查看返回值
- }
- }
- int n_write = write(fd,buf,strlen(buf));//用strlen计算buf大小
-
- char *readbuf;
- //开辟空间
- readbuf = (char *)malloc(sizeof(char)*n_write + 1);
- //清理资源之后重新打开 刷新指针光标在文件头部
- close(fd);
- //以可读可写方式打开
- fd = open("./file2",O_RDWR);
- //要读取的大小设置为100 查看返回值是实际读取数还是count
- int n_read = read(fd,readbuf,100);
- printf("read:%d,countext:%s\n",n_read,readbuf);
-
- close(fd);//资源清理
- return 0;
- }
编译运行
打开file2文件,可以看到指针光标在头部,如果不close(fd)重新open而是直接读取,将读取失败
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。