1:使用 dup2 实现错误日志功能
                 使用 write 和 read 实现文件的拷贝功能,注意,代码中所有函数后面,紧跟perror输出错误信息,要求这些错误信息重定向到错误日志 err.txt 中去
 代码:
  
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
void perror_dup();
int main(int argc, const char *argv[])
{
	umask(0000);
	perror_dup("umask");
	int rfd=open(argv[1],O_RDONLY);
	if(rfd==-1){
		perror_dup("ropen");
	//	return 1;
	}
	int wfd=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0666);
	if(wfd==-1){
		perror_dup("wopen");
	//	return 1;
	}
//	int buf[1]={0};文件本身也是字符,int本质只是一段内存,读取的时候是将数据存入到内存中
	char buf[1]={0};
	while(1){
		ssize_t returnval=read(rfd,buf,1);
		perror_dup("read");
		if(rfd==-1 || wfd==-1){break;}
		if(returnval==0){break;}//从普通文件读取时,没有数据读取时返回0
		write(wfd,buf,1);
		perror_dup("write");
	}	
	close(rfd);
	perror_dup("rfdclose");
	close(wfd); 
	perror_dup("wfdclose");
	return 0;
} 
void perror_dup(char *error)
{
	int pfd=open("./error.txt",O_APPEND|O_WRONLY);
	int retval=dup(2);
	dup2(pfd,2);
	perror(error);
	dup2(retval,2);
//	fflush(stderr);
	close(pfd); 
}
 
 
运行结果:
 1.输入被拷贝文件及拷贝文件错误日志:
2.拷贝文件错误日志:

3.正确拷贝日志:

  2:判断一个文件是否拥有用户可写权限,如果拥有,则去除用户可写权限,如果不拥有,则加上用户可写权限
                 权限更改函数:就是chmod函数,自己去man一下
                 要求每一次权限更改成功之后,立刻在终端显示当前文件的权限信息 :使用 ls -l显示(使用 system函数配合shell指令 ls -l 来实现)
 代码:
  
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
int main(int argc, const char *argv[])
{
	struct stat buf={0};
	stat(argv[1],&buf);
	mode_t mode=buf.st_mode;
	if((mode&S_IWUSR)==S_IWUSR){
		chmod (argv[1],(mode&(~S_IWUSR)));
	}
	else{
		chmod (argv[1],(mode | S_IWUSR));
	}
	system("ls -l");
	return 0;
}
 
 
运行结果:



















