1.使用 dup2 实现错误日志功能
使用 write 和 read 实现文件的拷贝功能,注意,代码中所有函数后面,紧跟perror输出错误信息,要求这些错误信息重定向到错误日志 err.txt 中去
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
int std_out = dup(2);
int fd3 = open("./err.txt",O_RDONLY | O_WRONLY |O_CREAT | O_TRUNC,0666);
perror("open3");
dup2(fd3,2);
int fd1 = open("./copy.bmp",O_RDONLY);
perror("open1");
int fd2 = open("./tar.bmp",O_WRONLY|O_CREAT|O_TRUNC,0666);
perror("open2");
int retval = 0;
char buff[128]={0};
while(1){
retval = read(fd1,buff,sizeof(buff));
perror("read");
if(retval == 0){break;}
write(fd2,buff,retval);
perror("write");
}
dup2(std_out,2);
close(fd1);
close(fd2);
close(fd3);
return 0;
}

2.判断一个文件是否拥有用户可写权限,如果拥有,则去除用户可写权限,如果不拥有,则加上用户可写权限
权限更改函数:就是chmod函数,自己去man一下
要求每一次权限更改成功之后,立刻在终端显示当前文件的权限信息 :使用 ls -l显示(使用 system函数配合shell指令 ls -l 来实现)
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
struct stat buf = {0}; //定义buf用来接受文件权限等信息
lstat("./autho.txt",&buf); //获取文件属性,并保存到buf里面去
mode_t mode = buf.st_mode;
if ((mode | S_IRUSR) == mode){
printf("./autho.txt文件拥有用户可写权限,已移除\n");
chmod("./autho.txt",mode &(~S_IRUSR));
system("ls -l ./autho.txt");
}else
{
printf("./autho.txt文件没有用户可写权限,已添加\n");
chmod("./autho.txt",mode | S_IRUSR);
system("ls -l ./autho.txt");
}
return 0;
}
