IO文件进程线程 5.8练习

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值