要求:按1的时候,通过printf输出数据,按2的时候,通过perror输出数据,按3的时候将输入写入文件中 同时通过dup2函数,将标准错误流重定向到错误日志,将文件流重定向到终端 4:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
void flie()
{
char buf[1000];
printf("输入数据\n");
int fp = open("output.txt",O_WRONLY | O_CREAT |O_TRUNC,0664);
int a=dup(1);
dup2(fp,1);
dup2(a,1);
fflush(stdout);
close(fp);
}
void error(){
char buf[1000];
printf("输入数据\n");
fgets(buf,sizeof(buf),stdin);
perror(buf);
}
void stdout_1(){
char buf[100];
printf("输入数据\n");
fgets(buf,sizeof(buf),stdin);
printf("%s",buf);
}
void error_diary()
{
int fd = open("error.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
if (fd == -1) {
perror("无法打开错误日志文件");
return;
}
// 将标准错误流重定向到错误日志
if (dup2(fd, STDERR_FILENO) == -1) {
perror("dup2 失败");
close(fd);
return;
}
close(fd); // 关闭文件描述符
}
int main(int argc, const char *argv[])
{
int a=0;
error_diary();
while(1){
printf("输入选项\n");
printf("1.标准输出流\n");
printf("2.标准错误流\n");
printf("3.文件流\n");
printf("4.退出\n");
scanf("%d",&a);
while(getchar()!=10);
switch(a){
case 1:
stdout_1();
case 2:
error();
break;
case 3:
flie();
break;
case 4:
exit(0);
}
}
return 0;
}
使用stat函数判断一个文件是否存在 同组人可执行 权限,如果存在则去除该权限,如果不存在则追加该权限 自己想办法查询 更改文件权限的函数是什么
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "用法: %s <文件名>\n", argv[0]);
return 1;
}
struct stat fileStat;
if (stat(argv[1], &fileStat) == -1) {
perror("stat");
return 1;
}
mode_t node_1 = fileStat.st_mode;
mode_t group = S_IXGRP;
if (node_1 & group) {
node_1 &= ~group;
} else {
node_1 |= group;
}
if (chmod(argv[1], node_1) == -1) {
perror("chmod");
return 1;
}
return 0;
}