第一题
int main(int argc, const char *argv[]){
int errFile=open("./error.txt",O_WRONLY | O_CREAT | O_TRUNC,0666);
int ret=dup2(errFile,2);
if(-1==ret)
perror("dup2");
int rd=open("./copy.c",O_RDONLY);
if(-1==rd)
perror("open");
int wt=open("./2.txt",O_WRONLY | O_CREAT | O_TRUNC,0666);
if(wt==-1)
perror("open");
while(1){
char c[1024];
ret=read(rd,c,1024);
if(-1==ret)
perror("read");
if(ret==0)break;
ret=write(wt,c,ret);
if(-1==ret)
perror("write");
}
ret=close(rd);
if(-1==ret)
perror("close");
ret=close(wt);
if(-1==ret)
perror("close");
return 0;
}
第二题
int main(int argc, const char *argv[]){
struct stat buf={0};
stat(argv[1],&buf);
char str[20]="ls -l ";
strcat(str,argv[1]);
mode_t mode = buf.st_mode;
if((mode|S_IWUSR)==mode){
chmod(argv[1],mode&~(1<<7));
system(str);
}
else{
chmod(argv[1],mode|1<<7);
system(str);
}
return 0;
}