opendir,closedir,readdir ,telldir的·使用详解及例子

linux下查找文件夹下的目录,扫描目录。得到要查找的东西  ,linux一切皆文件说的就是这个道理,其实和文件操作差不多

1,首先加入头文件

#include <sys/types.h>

#include <dirent.h>

2,opendir

DIR *opendir(const char *name);  //参数name 文件夹的名字

如果打开成功的话返回一个dir结构的指针

如果失败的话返回一个空指针

如果文件中的文件过多也可能打卡失败

3,readdir

     struct dirent *readdir(DIR *dirp);

The readdir function returns a pointer to a structure detailing the next directory entry in the directory
stream dirp. Successive calls to readdir return further directory entries. On error, and at the end of the
directory, readdir returns NULL. POSIX-compliant systems leave errno unchanged when returning
NULL at end of directory and set it when an error occurs.

函数成功的话返回一个指针,该指针的结构里保存着目录流中下一个目录项的资料,如果错误或者到了文件追后一个的话,返回NULL;

struct dirent 结构体中有两个元素

ino_t d_ino: The inode of the file//文件的inode节点
❑ char d_name[]: The name of the file//文件名

想要了解目录中的某个文件,需要了解stat的使用,我们下文介绍。

4,telldir

long int telldir(DIR *dirp);

函数返回文件流的第几位,后面可以用seekdir设置到第几位

void seekdir(DIR *dirp, long int loc);

5,closedir

函数关闭目录文件

int closedir(DIR *dirp);

It returns0 on success and –1 if there is an error.

返回0为成功,1失败。

6,下面为手写的printdir函数用于查看文件下面目录

#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL) {
fprintf(stderr,”cannot open directory: %s\n”, dir);       //判断dir是否是个文件夹

return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {              //一直读取dir里面的文件直到最后一个文件。
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode)) {
/* Found a directory, but ignore . and .. */
if(strcmp(“.”,entry->d_name) == 0 ||
strcmp(“..”,entry->d_name) == 0)
continue;
printf(“%*s%s/\n”,depth,”“,entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);     //递归调用,文件夹下面的文件再查找
}
else printf(“%*s%s\n”,depth,”“,entry->d_name);
}
chdir(“..”);
closedir(dp);
}

int main()
{
printf(“Directory scan of /home:\n”);
printdir(“/home”,0);
printf(“done.\n”);
exit(0);
}

运行结果

$ ./printdir
Directory scan of /home:
neil/
.Xdefaults
.Xmodmap
.Xresources
.bash_history
.bashrc
.kde/
share/
apps/
konqueror/
dirtree/
public_html.desktop
toolbar/
bookmarks.xml
konq_history
kdisplay/
color-schemes/








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值