通过 文件 IO 实现操作
cp 源文件 新文件名
步骤:
1.打开两个文件
源文件,只读打开
目标文件,可写打开,不存在就创建,存在就清空,赋予权限777
2.循环读取源文件,把读到的字符串暂存在 缓存区中,并获取返回值(实际读取的字符个数)
只要返回值大于0,就代表读到了字符,文件还没有结束
3.循环向目标文件写入字符串,把缓存区中暂存的字符串写入到目标文件中
// 文件IO实现cp功能
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
char buf[33] = ""; // 暂存数据
int fd_src, fd_dest; //定义两个文件操作
if (argc != 3) // 判断是否输入了进行两个操作的文件
{
printf("format:%s <srcfile> <destfile>\n", argv[0]);
return -1;
}
// 打开源,只读,
fd_src = open(argv[1], O_RDONLY);
if (fd_src < 0)
{
perror(" fd_src open error");
return -1;
}
// 打开目标文件,可写,不存在就创建,存在就清空,新建文件赋予权限 777
fd_dest = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0777);
if (fd_dest < 0)
{
perror(" fd_dest open error");
return -1;
}
ssize_t n; //
// 循环读源文件,只要读到内容,就写入到目标文件文件
// 一次性读取33个字符,
// n 来接收 read的返回值,为实际获取到的字符个数
// 只要返回值大于0,就代表读到了字符,文件还没有结束
while ((n = read(fd_src, buf, 33)) > 0)
{
write(fd_dest, buf, n); // 把buf中暂存的实际读取到的n个字符写入到dest中,
}
// 关闭文件
close(fd_src);
close(fd_dest);
return 0;
}