文件操作之3_扫描目录
来源:互联网 发布:淘宝双11抢购技巧 编辑:程序博客网 时间:2024/05/20 22:27
用到的系统调用函数如下:
lstat,opendir、readdir、chdir函数
1. lstat函数
函数原型:
#include<unistd.h>
#include <sys/stat.h>
#include<sys/types.h>
int lstat(const char *path,struct stat *buf);
lstat返回的是该符号链接本身的信息,stat结构成员如下:
st_mode 文件权限和文件类型信息
st_ino 与该文件关联的inode
st_dev 保存文件的设备
st_uid 文件属主的UID号
st_gid 文件属主的GID号
......
stat结构中返回的st_mode 标志以及与之关联的宏,他们定义在sys/stat.h中。
2. opendir函数
函数原型:
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
opendir函数的作用是打开一个目录并建立一个目录流。如果哟成功,它返回一个指向DIR结构的指针,该指针用于读取目录数据项。
3. readdir 函数
函数原型:
#include<sys/types.h>
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
dirent结构中包含的目录项内容以下部分:
ino_t d_ino: 文件的inode节点号。
char d_name[]:文件的名字。
测试函数:
#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);
return;
}
chdir(dir);
while((entry = readdir(dp))!=NULL)
{
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode))
{
if(strcmp(".",entry->d_name)==0 || strcmp("..",entry->d_name)==0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
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/zhangxm/c_programmer",0);
printf("done.\n");
exit(0);
}
函数结果:
zhangxm@zhangxm:~/c_programmer/dir_printdir$ ./printdir
directory scan of /home:
dir_read/
read.c
read
read.txt
dir_chown/
unlink.c
rmdir
.......
- 文件操作之3_扫描目录
- Linux文件操作-->扫描目录
- 学习笔记_操作文件和目录
- 扫描目录文件
- 目录文件操作实例[3]_使用文件预览显示文件信息
- 文件操作之遍历目录
- 文件操作之遍历目录
- JavaIO之文件目录操作
- ios文件操作之目录操作-NSFileManager
- python文件操作(1)--扫描某目录下的文件列表信息存入日志文件
- Java扫描指定目录文件
- 扫描目录下所有文件
- linux c 扫描文件目录
- python天天进步(3)--文件操作之遍历目录
- Python--文件操作之遍历目录
- python文件操作之遍历目录
- Linux教程 之-----文件与目录操作
- FTP文件操作之创建目录
- js实现瀑布流排序加载效果
- hdu 1022 Train Problem I (栈的应用)
- linux查找目录下的所有文件中是否含有某个字符串
- Tomcat服务器集群与负载均衡的实现
- 这一个还能用
- 文件操作之3_扫描目录
- MVVM模式下为Command传递多个参数
- 习近平在北大考察:青年要自觉践行社会主义核心价值观
- Mysql导出表结构及表数据mysqldump的用法
- 第十一周项目2(拓展)-职员信息(深复制)
- Android Camera子系统之Linux C应用开发者View
- 【js设计模式笔记---封装】
- nginx下yii伪静态处理
- Android中日期操作