拷贝形式: cp src.c(源文件) des.c(目标文件)
拷贝思路:
a. 打开源文件(src.c)
b. 将src.c读到buf里去
c. 打开/创建des.c(目标文件)
d. 将buf写入到des.c中
e. 用close关闭这两个文件
拷贝的操作指令:
a. gcc demo12.c -o mycp
b. ./mycp demo12.c ./new.c
功能代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<string.h>
#include<stdlib.h>
int main(int argc,char** argv)
{
int fdSrc; //文件描述符
int fdDes;
char readBuf[1024] = {0};
if(argc != 3)
{
printf("param error\n");
exit(-1);
}
fdSrc = open(argv[1],O_RDWR); //argv[1]为源的文件
int n_read = read(fdSrc,readBuf,1024);
fdDes = open(argv[2],O_RDWR|O_CREAT,0600);//O_CREAT表示文件不存在时创建文件
int n_write = write(fdDes,readBuf,strlen(readBuf));
close(fdSrc);
close(fdDes);
return 0;
}
优化后的代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<string.h>
#include<stdlib.h>
int main(int argc,char** argv)
{
int fdSrc; //文件描述符
int fdDes;
char* readBuf= NULL;
if(argc != 3)
{
printf("param error\n");
exit(-1);
}
fdSrc = open(argv[1],O_RDWR); //argv[1]为源的文件
int size = lseek(fdSrc,0,SEEK_END);
lseek(fdSrc,0,SEEK_SET);
readBuf = (char *)malloc(sizeof(char)*size+8);
int n_read = read(fdSrc,readBuf,size );
fdDes = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);//O_CREAT表示文件不存在时创建文件
int n_write = write(fdDes,readBuf,strlen(readBuf));
close(fdSrc);
close(fdDes);
return 0;
}
运行结果: