2024-03-05

作业要求:

  1.  使用write 和 read 实现 文件夹拷贝功能,不考虑递归拷贝
  2. 使用循环+fork的形式。创建一条进程链,链条上总共有100个进程 要求:程序不崩溃

作业1:使用write 和 read 实现 文件夹拷贝功能,不考虑递归拷贝

运行代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<dirent.h>
int main(int argc, const char *argv[])
{
	//打开拷贝文件夹
	DIR * dir = opendir(argv[1]);
	if(dir == NULL){
		perror("opendir");
		return -1;
	}
	//创建目标文件夹
	char sys[10]="mkdir ";
	strcat(sys,argv[2]);
	system(sys);	
	struct dirent *dnt;//文件夹结构体声明
	//文件夹文件遍历
	while((dnt = readdir(dir))!=NULL){
		//排除 . 和 ..
		if(strcmp(".",dnt->d_name)==0||strcmp("..",dnt->d_name)==0){
			continue;
		}
		//读文件
		char name_r[100] = {0}; 
		strcpy(name_r,argv[1]);
		strcat(name_r,"/");
		strcat(name_r,dnt->d_name);
	
		int rfp = open(name_r,O_RDONLY);
		if(rfp==-1){
			perror("open1");
			return -1;
		}
		//写文件
		char name_w[100] = {0};
		strcpy(name_w,argv[2]);
		strcat(name_w,"/");
		strcat(name_w,dnt->d_name);
		
		struct stat *mode;
		int stat1 = stat(name_r,mode);

		int wfp = open(name_w,O_WRONLY | O_TRUNC | O_CREAT,0666);

		char temp[1]={0};
		while(1){
			int res = read(rfp,temp,sizeof(temp));
			if(res <= 0){
				break;
			}
			write(wfp,temp,sizeof(temp));
		}

		close(rfp);
		close(wfp);

	}


	closedir(dir);
	return 0;
}
运行截图:

作业2:使用循环+fork的形式。创建一条进程链,链条上总共有100个进程 要求:程序不崩溃

运行代码:
#include<stdio.h>
#include<string.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 n=100;
	for(int i=0;i<n;i++){
		int res = fork();
		if(res == -1){
			return 1;
		}else if(res == 0){
			printf("%d\n",getpid());
			break;
		}else{
			sleep(1);
		}
	}
	return 0;
}
运行截图:
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值