【IO进程线程day3作业】

1.

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

int main(int argc, const char *argv[])
{
	DIR *dp=opendir("../opendir");
	int count=1;
	struct dirent *rp=NULL;
	int n;
	char buf[30]="";
	ssize_t res=0;
	struct dirent *abc[10];
	while(1)
	{	
		rp=readdir(dp);
		if(NULL==rp)
		{
			if(0==errno)
			{
				printf("目录读取完毕\n");
				break;
			}
			else
			{
				perror("opendir");
				return -1;
			}

		}

		if(rp->d_name[0]!='.')
		{
			abc[count-1]=rp;
			printf("[%d]%s\n",count++,rp->d_name);

		}

	}

	printf("请输入打印哪个文件的编号:");
	scanf("%d",&n);		
	int fd=open(abc[n-1]->d_name,O_RDONLY);
	if(fd<0)
	{
		perror("open");
		return -1;
	}
	while(1)
	{
		bzero(buf,sizeof(buf));
		res =read(fd,buf,sizeof(buf));
		if(0==res)
		{
			break;
		}
		write(1,buf,res);

	}

	close(fd);
	closedir(dp);
	return 0;
}

运行结果:

2.

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
void get(mode_t mode)
{
	char str[]="rwx";
	for(int i=0;i<9;i++)
	{
		if((mode&(0400>>i))==0)
		{
			putchar('-');
			continue;
			
		}
			putchar(str[i%3]);

	}
	putchar(10);
	
	return;
}
int main(int argc, const char *argv[])
{
	DIR *dp=opendir("../opendir");
	if(NULL==dp)
	{
		perror("opendir");
		return -1;
	}
	struct dirent *rp=NULL;
	while(1)
	{
		rp=readdir(dp);
		if(NULL==rp)
		{
			if(0==errno)
			{
				printf("目录文件读取完毕\n");
				break;
			}
			else
			{
				perror("readdir");
				return -1;
			}

		}
		printf("文件名:%s\n",rp->d_name);
		struct stat buf;
		int res=stat(rp->d_name,&buf);
		if(res<0)
		{
			perror("stat");
			return -1;
		}
		//打印文件权限
		get(buf.st_mode);
		//硬连接数
		printf("link=%ld\n",buf.st_nlink);
		//文件所属用户名 所属组用户名
		printf("%d\t%d\n",buf.st_uid,buf.st_gid);
		//文件大小
		printf("size=%ld\n",buf.st_size);
		//时间
		printf("time=%ld\n",buf.st_ctime);
		printf("-------------\n");

	}
	closedir(dp);
	
	


	return 0;
}

运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值