1.cat实现
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
//实现cat命令
int main(int argc, const char *argv[])
{
char r_buf[1000];
if(argv<3)
{
printf("请输入两个文件夹参数");
return -1;
}
for(int i=1;i<argc;i++)
{
memset(r_buf,0,sizeof(r_buf));
int k=open(argv[i],O_RDWR);
if(k==-1)
{
perror("文件打开失败");
return-1;
}
while(1)
{
int r=read(k,r_buf,sizeof(r_buf)-1);
if(r==0)
{
break;
}
printf("%s",r_buf);
}
}
close(r);
return 0;
}
2.cp命令的实现
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
if(argc!=3)
{
printf("只要求传入两个文件");
}
char buf[100];
int fd1=open(argv[1],O_RDWR);
if(fd1==-1)
{
perror("文件1打开失败");
}
int fd2=open(argv[2],O_RDWR | O_CREAT);
if(fd2==-1)
{
perror("文件2打开失败");
}
while(1)
{
memset(buf,0,sizeof(buf));
int rd=read(fd1,buf,sizeof(buf));
if(rd==0)
{
break;
}
int wr=write(fd2,buf,strlen(buf));
if(wr==0)
{
printf("写入失败");
}
}
close(fd1);
close(fd2);
return 0;
}
3.实现diff命令
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#define N 500
int main(int argc, const char *argv[])
{
if (argc != 3)
{
printf("请输入两个文件名\n");
return 1;
}
int fd1 = open(argv[1], O_RDONLY);
if (fd1 == -1)
{
perror("文件1打开失败");
return 1;
}
int fd2 = open(argv[2], O_RDONLY);
if (fd2 == -1)
{
perror("文件2打开失败");
close(fd1);
return 1;
}
char buf1[N];
char buf2[N];
int read1, read2;
while(1)
{
read1 = read(fd1, buf1, N);
read2 = read(fd2, buf2, N);
if (read1 != read2)
{
printf("不相同\n");
}
else
{
printf("相同\n");
}
close(fd1);
close(fd2);
return 0;
}
}