在Linux中cp指令可以复制文件,当然我们也可以通过自己编程来完成cp指令;
具体思路是:
1.打开源文件,判断argc<3,argv[0]为可执行程序的名字,argv[1]为源文件,argv[2]为目标文件。
2.打开需要读取的文件,统计文件大小,将需要读取的文件读入到临时的字符串数组空间。
3.并且创建一个新文件,将读到的数据写入到新创建的文件即可。
4.关闭文件
来看具体代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
int fdsrc;
char* buf=NULL;
int fddes;
if(argc !=3)
{
printf("param error\n");
exit(-1);
}
fdsrc=open(argv[1],O_RDWR); //以只读的方式打开第一个文件
int size=lseek(fdsrc,0,SEEK_END); //计算文件大小
lseek(fdsrc,0,SEEK_SET); //将光标移到文件开头
buf=(char*)malloc(sizeof(char)*size+7); //为缓存区申请内存空间
int n_read= read(fdsrc,buf,size); //读取源文件内容到缓存去
fddes=open(argv[2],O_RDWR|O_CREAT,0600); //打开目标文件
int n_write=write(fddes,buf,strlen(buf)); //将缓存区内容写到目标文件
close(fdsrc); //关闭文件
close(fddes);
return 0;
}