2023.04.11

该程序读取指定目录,使用readdir函数列出所有非隐藏文件和目录,将文件名写入到给定的文件中。然后,程序从这个文件中读取内容并显示在屏幕上。主要涉及文件系统操作和文件描述符的使用。
摘要由CSDN通过智能技术生成

作业:使用readdir来将目录中的链接文件显示出来,并写入到一个文件内部,再将文件中的内容显示到屏幕上

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

//读取文件的内容,输出到屏幕上
void do_file(int fd)
{
	char buf[100] = {0};
	int n = 0;
	while(1)
	{
		memset(buf,0,sizeof(buf));

		//读取文件的内容,并返回
		n = read(fd,buf,sizeof(buf));
		
		//当n=0时,读取到文件尾部
		if(n == 0)
		{
			break;
		}
		write(STDOUT_FILENO,buf,sizeof(buf));
	}
	return;
}

void readdir_file(DIR *dp,int fd)
{
	struct dirent *dt;

	while(1)
	{
		dt = readdir(dp);
		if(NULL == dt)
			break;
		if(dt -> d_name[0] == '.')
			continue;
		if(dt -> d_type == DT_DIR || dt -> d_type == DT_REG)
		{
			if(write(fd,dt->d_name,strlen(dt->d_name))<0)
			{
				perror("write");
			}
			printf("reg file:%s\n",dt -> d_name);
		}
	}
}

int main(int argc, const char *argv[])
{
	int fd;
	DIR *dp;


	if(argc != 3)
	{
		fprintf(stderr,"usage:%s readdir.txt\n",argv[0]);
		return -1;
	}
	
	//打开文件

	fd = open(argv[1],O_RDWR);
	if(fd<0)
	{
		perror("Fail to open");
		return -1;
	}
	
	dp = opendir(argv[2]);
	if(NULL == dp)
	{
		perror("Fail to opendir");
		return -1;
	}

	readdir_file(dp,fd);

	//操作文件
	do_file(fd);

	close(fd);
	closedir(dp);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值