题目1:
使用 dup2 实现错误日志功能使用 write 和 read 实现文件的拷贝功能,注意,代码中所有函数后面,紧跟perror输出错误信息,要求这些错误信息重定向到错误日志 err.txt 中去
#include <stdio.h> #include <unistd.h> #include <fcntl.h> int main(int argc, char const *argv[]) { char buf[64]={0}; int rfd = open("file.txt",O_RDONLY); int wfd = open("file2.txt",O_WRONLY | O_CREAT, 0666); int errfd = open("err.txt",O_WRONLY | O_CREAT, 0666); dup2(errfd,2); if(wfd == -1 || rfd == -1 || errfd == -1) { perror("error"); return 1; } while(1) { ssize_t Rret = read(rfd,buf,64); if(Rret == 0) { break; } write(wfd,buf,Rret); perror("error"); } close(rfd); close(wfd); close(errfd); return 0; }
题目2:
判断一个文件是否拥有用户可写权限,如果拥有,则去除用户可写权限,
如果不拥有,则加上用户可写权限
权限更改函数:就是chmod函数,自己去man一下
要求每一次权限更改成功之后,立刻在终端显示当前文件的权限信息 :
使用 ls -l显示(使用 system函数配合shell指令 ls -l 来实现)
#include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <strings.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/stat.h> #include <stdlib.h> int main() { char *file = "./file2.c"; if (access(file, W_OK) != -1) { // 文件拥有用户可写权限 chmod(file, 0466); // 去除用户可写权限 } else { // 文件没有用户可写权限 chmod(file, 0666 | S_IWUSR); // 添加用户可写权限 } system("ls -l file2.txt"); return 0; }