#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
void show_pro()//用void一般不出错
{
char path[256]={0};
getcwd(path,sizeof(path));
printf("[linux@ubuntu:%s$]",path);
fflush(stdout);
}
//cp 1.c 2.c
int do_cp(char * src,char* dst)//想表达对错,所以返回值类型用int
{
int srcfd = open(src,O_RDONLY);
int dstfd = open(dst,O_WRONLY|O_CREAT|O_TRUNC,0666);
if(-1 == srcfd|| -1 ==dstfd)
{
perror("do_cp error");
return -1;//0是成功,非零是失败
}
while(1)
{
char buf[4096]={0};//一般是1k到4k,4k快点,所以写了4096
int rd_ret = read(srcfd,buf,sizeof(buf));
if(rd_ret<=0)
{
break;
}
write(dstfd,buf,rd_ret);
}
close(srcfd);
close(dstfd);
return 0;//成功了,返回0
}
// cd cd /home
int do_cd(char * path)//cd后面啥也没写,意味着进入/home/linux这个路径下
{
int ret = 0;
if(NULL == path)//判断cd命令后面有没有路径
{
ret = chdir("/home/linux");
}
else
{
ret = chdir(path);
if(0!=ret)
{
perror("do_cd");
}
}
return ret;//同理看是否成功
}
// touch 1.c
int do_touch(char * filename)
{
int fd = open(filename,O_WRONLY|O_CREAT|O_TRUNC,0666);
if(-1 ==fd)
{
perror("do_touch");
return -1;
}
return -1;
}
int main(int argc, char *argv[])
{
while(1)
{
show_pro();
char cmd[256]={0};
fgets(cmd,sizeof(cmd),stdin);//\n
cmd[strlen(cmd)-1]='\0';
if(0 == strlen(cmd))
{
continue;
}
char * arg[4]={NULL};
arg[0]=strtok(cmd," ");
arg[1]=strtok(NULL," ");
arg[2]=strtok(NULL," ");
arg[3]=strtok(NULL," ");
if(0== strcmp("cp",arg[0]))
{
//cp 1.c 2.c
do_cp(arg[1],arg[2]);
}
else if(0 == strcmp("cd",arg[0]))
{
// cd cd /home
do_cd(arg[1]);
}
else if(0==strcmp("touch",arg[0]))
{
// touch 1.c
do_touch(arg[1]);
}
else
{
printf("cmd error\n");
}
}
return 0;
}