Linux下实现cp指令的功能:
头文件可以通过使用 man 手册查询
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char **argv)
{
int fdsr; // 创建两个文件描述符
int fdcr;
char *buf = NULL; // 用于存放文件数据
if(argc != 3) // cp a b 这样参数有三个才为正确,其他都是操作有误
{
printf("操作参数有问题\n");
perror("why :");
exit(-1);
}
fdsr = open(argv[1],O_RDWR); //打开第一个参数的文件,设置为可读可写
if(fdsr == -1) // 检验文件是否打开失败,失败返回 -1
{
printf("open failed\n");
}
int size = lseek(fdsr,0,SEEK_END); //光标从末尾开始,返回值为文件的数据长度
lseek(fdsr,0,SEEK_SET); //重置光标位置到开头位置,也就是读完整个数据后开始的位置
buf = (char *)malloc(sizeof(char)*size + 8); // 开辟存放文件数据的空间大小
int n_read = read(fdsr,buf,size); // 读入数据
fdcr = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600); // 打开第二个参数文件
int n_write = write(fdcr,buf,strlen(buf)); // 把fdsrc读入buf的数据,输送到fdcr这个文件
//从而实现文件拷贝cp指令
close(fdsr); //操作完一定要关闭文件,防止损坏文件
close(fdcr);
return 0;
}
还没有评论,来说两句吧...