2024.6.11 1.获取指定目录下的文件属性。2.利用父进程和子进程复制图片

1.要求将指定路径下,所有文件(除了隐藏文件)的权限及最后一次的访问时间提取出来,写入到file.txt中

代码

#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

int main(int argc, const char *argv[])
{
	DIR* dp = opendir("./2_day/");
	FILE* fp = fopen("./file.txt","w");
	char c;//用来写入换行或者制表符的
	struct stat buf;//配合stat函数获取文件的权限和修改时间
	struct tm* info;
	char datetime_string[20];//装时间
	if(dp == NULL)
	{
		perror("opendir");
		return -1;
	}

	while(1)
	{
		struct dirent* a1 = readdir(dp);
		if(NULL == a1)
		{
			break;
		}
		if(a1->d_name[0]!='.')
		{
			fprintf(fp,"%-20s",a1->d_name);//获取文件名字
			c = '\t';
			fprintf(fp,"%c",c);//写入制表符,让文件名字和权限有间隔增加可读性
			stat(a1->d_name,&buf);//获取文件属性
			fprintf(fp,"%o",buf.st_mode&0777);//获取权限
			c = '\t';
			fprintf(fp,"%c",c);

			//获取时间
			time_t Time = buf.st_atime;
			info = localtime(&Time);// 将秒数转换成本地时间
			 // 格式化输出年月日 时:分:秒
   			strftime(datetime_string, sizeof(datetime_string), "%Y-%m-%d %H:%M:%S"\
					 ,info);
			fprintf(fp,"%s",datetime_string);

			c='\n';
			fprintf(fp,"%c",c);//写入换行

		}
	}

	closedir(dp);
	fclose(fp);
	return 0;
}

运行结果

2.使用文件IO对图片进行拷贝。要求子进程拷贝后半部分,父进程拷贝前半部分。要求拷贝到一个文件中。拷贝完毕后与源文件一致。

代码

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, const char *argv[])
{

	int fp=open("./qq.png",O_RDONLY);
	int cfp=open("./copy.png",O_WRONLY|O_CREAT|O_TRUNC,0770);
	off_t size = lseek(fp,0,SEEK_END);//获取文件大小
	off_t size_head = size / 2;
	off_t size1;
	char c;
	ssize_t num;

	lseek(fp,0,SEEK_SET);//将文件偏移修改到文件头

	pid_t pid=fork();//创建子进程
	printf("pid=%d\n",pid);
	if(pid!=0)
	{
		while(1)
		{
			num = read(fp,&c,1);
			write(cfp,&c,num);
			size1 = lseek(fp,0,SEEK_CUR);
			if(size1==size_head)
			{
				printf("前半部分复制完成\n");
				break;
			}
		}
	}
	else if(pid == 0)
	{
		sleep(1);//确保子进程后运行
		while(1)
		{
		num = read(fp,&c,1);
		write(cfp,&c,num);
		if(num==0)
		{
			printf("后半部分复制完成\n");
			break;
		}
	}

	}


	close(cfp);
	close(fp);
	return 0;
}

运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值