目录
一、read和write(系统IO)
代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
#define ONCE_GET_SIZE 1
int Get_File_Descriptor(const char *pathname, int flags, mode_t mode); // 获取文件描述符
int Read_File_Date(int file_fd, char *buf, size_t size); // 读数据
int Write_File_Date(int file_fd, char *buf, size_t size); // 写数据
int Close_File_Descriptor(int file_fd); // 关闭文件
int Copy(int fdin, int fdout, char *buf); // 文件拷贝功能
/*
功能: 获取文件描述符
pathname: 文件路径
flags: 说明此函数的多个选择项
mode: 新建文件的访问权限,等于0则表示不需要创建
返回值: 错误返回-1,正确返回文件描述符
*/
int Get_File_Descriptor(const char *pathname, int flags, mode_t mode)
{
int fd;
if (!mode)
{
fd = open(pathname, flags);
}
else
{
umask(0000);
fd = open(pathname, flags, mode);
}
if (fd == -1)
{
perror("open error ");
return -1;
}
return fd;
}
/*
功能: 读取数据
file_fd: 要读文件的文件描述符
buf: 存放读取的数据
size: 读取数据的大小
返回值: 错误返回-1,正确返回读出的字节数量
*/
int Read_File_Date(int file_fd, char *buf, size_t size)
{
size_t read_ret = read(file_fd, buf, size);
if (read_ret == -1)
{
perror("write error");
return -1;
}
return read_ret;
}
/*
功能: 写入数据
file_fd: 要写文件的文件描述符
buf: 存放写入的数据
size: 读取数据的大小
返回值: 错误返回-1,正确返回写入的字节数量
*/
int Write_File_Date(int file_fd, char *buf, size_t size)
{
size_t write_ret = write(file_fd, buf, size);
if (write_ret == -1)
{
perror("write error");
return -1;
}
return write_ret;
}
/*
功能: 文件拷贝
fdin: 源文件
fdout: 目标文件
buf: 数据
返回值: 错误返回-1,正确返回0
*/
int Copy(int fdin, int fdout, char *buf)
{
ssize_t read_size, write_size;
while ((read_size = Read_File_Date(fdin, buf, ON