Linux 系统IO函数
1.open函数
//头文件
#include
#include
#include
//定义
//open 返回文件的描述符,pathname : 需要打开的文件 flags: 以读写或者其他方式打开
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
int openat(int dirfd, const char *pathname, int flags);
int openat(int dirfd, const char *pathname, int flags, mode_t mode);
flags:
O_RDONLY:以只读方式打开文件
O_WRONLY:以只写方式打开文件
O_RDWR:以读写方式打开文件
O_CREAT:如果文件不存在,则创建一个文件,并且需要指定文件的属性(umask)
O_TRUNC:如果文件已经存在,并且文件可写,会把文件截断为0
O_APPEND:以追加写的方式写文件
ex:
#include
#include
int fd = -1;
fd = open("path", O_RDWR);
if(fd == -1);
printf("fd = %d, error:%d %s", fd, errno, strerror(errno));
2.read函数
//头文件
#include
//函数原型 从打开的文件描述符fd中读取count大小的内容,返回读取的字节数,把内容存放在buf中,如果返回0,代表读到文件结尾,如果返回-1 最好设置errno变量
ssize_t read(int fd, void *buf, size_t count);
3.write函数
//头文件
#include
//函数原型 从打开的文件描述符fd文件中写入count大小的内容
ssize_t write(int fd, const void *buf, size_t count);
4.close函数
//头文件
#include
//函数原型 关闭文件句柄
int close(int fd);
实现拷贝函数
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
int fd1 = -1;
int fd2 = -1;
char buf[1024] = {0};
int len = 0;
if(argc < 2)
printf("input params failn");
fd1 = open(argv[1], O_RDWR);
if(fd1 == -1)
printf("errno:%d fd = %d %sn", errno, fd1,strerror(errno));
fd2 = open(argv[2], O_RDWR | O_CREAT, 0644);
if(fd2 == -1)
printf("errno:%d fd=%d %sn", errno, fd2, strerror(errno));
while(len = read(fd1, buf, sizeof(buf))){
write(fd2, buf, len);
}
close(fd1);
close(fd2);
return 0;
}