linux自己实现CP命令代码
输入命令: cp text1.c text2.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()//可直接传参
{
char *name="text1.c";
char *name2="text2.c";
// int fdbuf[128];
int fd;
ssize_t n_write;
struct stat statbuf;
int Size;
if(stat(name,&statbuf) == 0)//判断文件是否存在
{
printf("stat success\n");
Size=statbuf.st_size;
printf("file size:%ld\n",Size);
}
int fdbuf[Size];
fd = open(name,O_RDWR);
if(fd!=-1)
{
printf("open success\n");
}
int n_read = read(fd,&fdbuf,Size);
if(n_read != 0)
{
printf("read success\n");
}
else if(n_read==-1)
{
perror("read failed:");
}
int fd2 = open(name2,O_RDWR|O_CREAT|O_TRUNC,0600);
n_write = write(fd2,&fdbuf,Size);
if(n_write == -1)
{
perror("write failed:");
}
else
{
printf("write succes\n");
}
close(fd);//最后要关闭两个文件
close(fd2);
return 0;
}