1.使用dup2实现错误日志功能
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int error_fd=open("./demo3.txt",O_WRONLY | O_CREAT | O_TRUNC,0664);
perror("error:");
dup2(error_fd,STDERR_FILENO);
int read_fd=open("./demo2.c",O_RDONLY);
perror("error:");
int write_fd=open("./copy_demo2.c",O_WRONLY | O_CREAT | O_TRUNC,0664);
perror("error:");
char c;
while(1)
{
int res=read(read_fd,&c,1);
if(res==0)
{
perror("read:");
break;
}
write(write_fd,&c,1);
perror("write:");
}
close(read_fd);
perror("close:");
close(write_fd);
perror("close:");
close(error_fd);
perror("close:");
return 0;
}
2.判断文件是否拥有写权限,若拥有,则去除,若不拥有,则添加
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
struct stat buf;
char ls[20]="ls -l ";
stat(argv[1],&buf);
mode_t mode=buf.st_mode;
if((mode|S_IWUSR)!=mode){
chmod(argv[1],0777);
system(strcat(ls,argv[1]));
}
else{
chmod(argv[1],0555);
system(strcat(ls,argv[1]));
}
return 0;
}