5.8 作业

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>


int main(int argc, const char *argv[])
{
	//使用 dup2 实现错误日志功能
	int log = open("./err.txt",O_WRONLY | O_CREAT | O_APPEND,0666);
	if(log == -1)
	{
		perror("open");
		return 1;
	}
	int save_stderr = dup(2); //保存sdterr
	int fp_open = dup2(log,2); //重定向stderr
	if (fp_open == -1)
	{
		perror("dup2");
		return 1;
	}
	close(log);
	//使用 write 和 read 实现文件的拷贝功能
	int rfd = open(argv[1],O_RDONLY);
	if(rfd == -1)
	{
		perror("rfd");
		return 1;
	}
	int wfd = open(argv[2],O_WRONLY | O_CREAT | O_TRUNC,0666);
	if(wfd == -1)
	{
		perror("wfd");
		return 1;
	}
	char buf[128] = {0};
	while(1)
	{
		int retval = read(rfd,buf,128);
		if (retval == 0)
	{
			break;
		}
		write(wfd,buf,retval);
	}
	close(rfd);
	close(wfd);
	return 0;
}

2

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>

//判断一个文件是否拥有用户可写权限,如果拥有,则去除用户可写权限,如果不拥有,则加上用户可写权限

int main(int argc, const char *argv[])
{
	// 判断一个文件是否拥有用户可写权限
	struct stat buf = {0};
	stat(argv[1],&buf);//获取argv[1]文件的属性,并将属性保存到buf里面去
		mode_t mode = buf.st_mode;
    	mode_t new_mode ; //用于修改写权限
	// 判断依据为:如果一个变量里面,某个bit是1的话,|该bit为的1话,该变量是不变的
	if((mode | S_IWUSR) == mode)
	{
		printf("%s文件拥有用户可写权限\n",argv[1]);
		new_mode = mode & ~(S_IWUSR);  //用于去除写权限
	}
	else
	{
		new_mode = mode | S_IWUSR;   //用于添加写权限
	}
	int a = chmod(argv[1],new_mode);  //修改权限
	if (a==-1)
	{
		perror("chmod");
		return 1;
	}
	//在终端显示当前文件的权限信息
    if (system("ls -l") == -1) 
	{  
        perror("system");  
        return 1;  
    }  
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值