opendir和readdir

代码

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

int main(int argc, char *argv[])
{
	if(argc < 2)
	{
		printf("usage: ./a.out filename\n");
		exit(-1);
			
	}
	DIR *p = NULL;
	p = opendir(argv[1]);
	if (NULL == p)
	{
		perror("opendir");
	}
	
	struct dirent *p_read = NULL;
	while(1)
	{
		p_read = readdir(p);
		if(NULL == p_read)
		{	
			perror("readdir");
			printf("the end of the directory stream\n");
			exit(-1);
		}
		else
		{
			printf("d_name is %s \n",p_read->d_name);
		}
	
	}
	

	return 0;
	
}

opendir和readdir

先关于opendir的一点点记录

对于opendir的话,看完网课教程后面,我再试着根据仅有的记忆,自己通过man手册去写一个简单的测试代码。

SYNOPSIS
#include <sys/types.h>
#include <dirent.h>

   DIR *opendir(const char *name);

这里就是man手册里面的解释。
得出的2个信息:
1.opendir返回值是一个DIR*类型的东西
2.opendir是一个输入型函数。

然后我开始写测试代码的时候就纳闷了,DIR类型是什么东西?
然后我自己傻乎乎的真的自己定义了一个struct dir* 类型的一个指针。后面我发现我错了,其实你的dirent.h的头文件里面应该就对DIR*这个类型有定义可以使用的。
当我把dirent.h注释掉之后就提示

dir.c:18:2: error: unknown type name ‘DIR’ DIR *p = NULL;

所以我们只要include了dirent.h头文件的话就可以使用这个DIR*类型了。
虽然这可能是一个非常简单非常基础的问题,我还把它记录下来了,但是一点一滴也是积累嘛。

接着是readdir

DESCRIPTION
The readdir() function returns a pointer to a dirent structure repre‐
senting the next directory entry in the directory stream pointed to by
dirp. It returns NULL on reaching the end of the directory stream or
if an error occurred.

man手册里面是这样描述的。
讲真,如果我不是把整段description拿去翻译的话我估计还是没懂的,会理解错。我刚开始的时候是没有用while(1)这个循环去把东西全部都读出来的,我只是奇怪诶为什么只是读出了一项呢?后面我就一直复制粘贴了很多遍,把东西都读出来了。

经过金山词霸的翻译之后我发现我理解错误了,description里面的representing的意思不是代表的意思,是重现的意思,re-重新,present-展现。
所以整个description说的是这个readdir函数返回的是一个指针,指向dirent structure的,然后会再次把下一个目录入口呢又放到drip指向的文件流。
我觉得我还是翻译的不准确。看词霸的翻译:

Readdir()函数将指针返回到Dirp结构,该结构会将下一个目录条目重新设置在由Dirp指向的目录流中。

这会就懂了。

然后我百度了一下,发现我这代码其实就是ls功能的代码。。。。

好了就酱紫吧。

发布了38 篇原创文章 · 获赞 1 · 访问量 1044

猜你喜欢

转载自blog.csdn.net/qq_40897531/article/details/103572222