IOday3

文章介绍了如何在C程序中利用`dup2`函数实现错误日志功能,并通过`chmod`函数检查并调整文件的写权限。两个示例展示了处理I/O流和文件权限操作的技术细节。
摘要由CSDN通过智能技术生成

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;	
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值