Linux 系统 IO之 read write 函数
文章目录
1. read 函数
1.1 头文件包含
// 记忆方法:unistd <--> uinx std
#include <unistd.h>
1.2 函数原型
// size_t:无符号整型
// ssize_t:有符号整型 <==> int
ssize_t read(int fd, void *buf, size_t count);
1.3 函数功能
read
函数从给定的文件描述符指定的文件中,读取 count
个字节的数据,存放至 buf中。
1.4 函数返回值
- 返回
-1
:文件读取失败,设置errno
指出失败原因 - 返回
0
:文件读取结束 - 返回
>0
: 本次所成功读取的字节数
1.5 形参解释
int fd
:指定要读写的文件描述符void* buf
:缓冲区,一般是一个数组,用于存放读取的内容size_t count
:一次要读取的最大字节数
2. write 函数
2.1 头文件包含
#include <unistd.h>
2.2 函数原型
ssize_t write(int fd, const void *buf, size_t count);
2.3 函数功能
write
函数将 buf
中的 count
字节数据写入指定文件描述符的文件中。
2.4 函数返回值
- 返回
-1
:文件写失败,错误代码存至errno
中 - 返回
0
:count
参数为 0 时,返回 0 ,此时没有写入任何数据 - 返回
>0
: 本次所成功写入文件的字节数
2.5 形参解释
int fd
:指定要写入的文件描述符void* buf
:缓冲区,一般是一个数组,读取存放于该数组的内容存放于文件中size_t count
:要写入的实际字节数
3. 案例程序:读写一个已存在文件内容至新建文件中
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
int fd_rd = open("annNote", O_RDONLY);
if( -1 == fd_rd){
perror("open read file");
exit(1);
}
// 如果文件不存在,新建
// 如果文件存在,则截断文件内容(清空)
int fd_wr = open("annWrite", O_RDWR | O_CREAT | O_TRUNC, 0777);
if(-1 == fd_wr){
perror("open write file");
exit(-1);
}
char buf[1024] = {0};
int readSize = -2;
int writeSize = -2;
while(1){
readSize = read(fd_rd, buf, 1024);
if(0 == readSize)
break;
if( -1 == readSize){
perror("read");
exit(-1);
}
// 一定要注意,第三个参数是要实际写如文件的字节数
writeSize = write(fd_wr,buf, readSize);
if( -1 == writeSize){
perror("write");
exit(-1);
}
}
// 记得关闭打开的文件描述符
if(-1 == close(fd_rd)){
perror("close fd_rd");
exit(-1);
}
if(-1 == close(fd_wr)){
perror("close fd_wr");
exit(-1);
}
return 0;
}