Work20230504

该程序首先遍历指定目录,忽略隐藏文件,打印文件名。然后用户输入文件编号,程序读取并显示相应文件内容。另外,它还展示了一个函数用于根据文件模式获取权限信息,并打印文件的链接数、所有者、组、大小及创建时间。
摘要由CSDN通过智能技术生成

作业一

//作业一
//所用函数有
//opendir readdir closdir
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(){
	//打开目录
	DIR *dirStr=opendir("../program_DS/");
	if(dirStr==NULL){
		printf("目录打开失败\n");
		return -1;
	}
	
	//获取目录内的内容
	struct dirent *det;
	int count=1;
	char *name[256];
	while(1){
		det=readdir(dirStr);
	
		if(NULL==det){
			if(0==errno){
				printf("目录文件读取完毕\n");
				break;
			}else
			{
				perror("readdir");
				return -1;
			}
		}
		//检测到隐藏文件夹则不打印
		if(det->d_name[0]!='.'){
			name[count]=det->d_name;
			printf("[%d] %s\n",count++,det->d_name);
		}


	}
//将文件内容显示在终端上
//利用文件IO中的write函数,将文件写到终端上
	printf("选择要打开的文件标号:");
	int lable;
	scanf("%d",&lable);
//1.利用open函数打开文件
	
	int flable =open(name[lable],O_RDONLY);
	if(flable==-1){
		perror("error");
	}
	ssize_t res=0;
	char buf[32]="";
	while(1){
		bzero(buf,sizeof(buf));
		res=read(flable,buf,sizeof(buf));//2.读取
		if(0==res) break;

		write(1,buf,res);//3.打印到终端

	}
	
	close(flable);
	closedir(dirStr);
	return 0;
}

作业二

//作业二
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
char *permissionInfo(mode_t mode){

	static char getPer[10]="";
	char per[]="rwx";
	for(int i=0;i<9;i++){
		if((mode&(0400>>i)==0)){
			getPer[i]='-';
			continue;
		}
		getPer[i]=per[i%3];
	}
	return getPer;
	
}
int main(){

	struct tm *info=NULL;

	struct stat buf;
	if(stat("./pro.c",&buf)<0)
	{
		perror("stat");
		return -1;
	}

//	printf("mode:%o\n",buf.st_mode);
	printf("%s",permissionInfo(buf.st_mode));
	putchar(10);
	printf("link:%ld\n",buf.st_nlink);

	printf("uid:%d gid:%d\n",buf.st_uid,buf.st_gid);

	printf("size:%ld\n",buf.st_size);

	//printf("time:%ld\n",buf.st_ctime);
	info=localtime(&buf.st_ctime);
	if(info==NULL) printf("获取失败");

	printf("%d",info->tm_year+1900);
	printf("-%02d",info->tm_mon+1);
	printf("-%02d",info->tm_mday);
	printf(" %02d",info->tm_hour);
	printf(":%02d",info->tm_min);
	printf(":%02d",info->tm_sec);
	putchar(10);

	return 0;
}

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值