需求:
使用回调函数遍历指定目录。
实现:
函数实现处,橙色部分为重点,即路径变量控制:
点击(此处)折叠或打开
-
/********************************************************
-
*filename : scan.c
-
*descriptor : source file - scan the directory that given
-
*autor : Rocky
-
*date : 2017-06-22
-
********************************************************/
-
-
#include "scan.h"
-
-
#ifdef _MAN_READDIR
-
//On Linux, the dirent structure is defined as follows:
-
-
struct dirent {
-
ino_t d_ino; /* inode number */
-
off_t d_off; /* not an offset; see NOTES */
-
unsigned short d_reclen; /* length of this record */
-
unsigned char d_type; /* type of file; not supported
-
by all filesystem types */
-
char d_name[256]; /* filename */
-
};
-
/*
-
d_type:
-
-
DT_BLK This is a block device.
-
DT_CHR This is a character device.
-
DT_DIR This is a directory.
-
DT_FIFO This is a named pipe (FIFO).
-
DT_LNK This is a symbolic link.
-
DT_REG This is a regular file.
-
DT_SOCK This is a UNIX domain socket.
-
DT_UNKNOWN The file type is unknown.
-
*/
-
#endif
-
-
int start_scan(const char *dirname)
-
{
-
DIR *dir_ptr;
-
struct dirent *ptr;
-
char deeper_dir[PATH_MAX] = {0};
-
-
dir_ptr = opendir(dirname);
-
if (NULL == dir_ptr)
-
{
-
perror("opendir error");
-
return -1;
-
}
-
-
while ((ptr = readdir(dir_ptr)))
-
{
-
/* ignore the "." nad ".." */
-
if (!strcmp(ptr->d_name, ".") || !(strcmp(ptr->d_name, "..")))
-
continue;
-
-
printf("name is %s\n", ptr->d_name);
-
if (DT_REG == ptr->d_type)
-
{
-
printf("+++++ I am a regule file\n");
-
}
-
else if (DT_DIR == ptr->d_type)
-
{
-
printf("----- I am a directory\n");
-
-
strcpy(deeper_dir, dirname);
-
strcat(deeper_dir, "/");
-
strcat(deeper_dir, ptr->d_name);
-
-
start_scan(deeper_dir);
-
}
-
}
-
-
closedir(dir_ptr);
-
-
return 0;
-
}
头文件定义:
-
/********************************************************
-
*filename : scan.h
-
*descriptor : head file - scan the directory that given
-
*autor : Rocky
-
*date : 2017-06-22
-
********************************************************/
-
-
#ifndef _SCAN_H_
-
#define _SCAN_H_
-
-
#include <stdio.h>
-
#include <dirent.h>
-
#include <string.h>
-
#include <sys/types.h>
-
-
#ifndef PATH_MAX
-
#define PATH_MAX 256
-
#endif //PATH_MAX
-
-
int start_scan(const char *dirname);
-
-
#endif // _SCAN_H_
-
/**********************************************************
-
*filename : main.c
-
*autor : Rocky
-
*date : 2017-06-22
-
************************************************************/
-
-
#include "scan.h"
-
-
int main(int argc, char *argv[])
-
{
-
if (argc < 2)
-
{
-
printf("Usage : %s dirname\n", argv[0]);
-
return -1;
-
}
-
-
printf("dirname is %s\n", argv[1]);
-
start_scan(argv[1]);
-
-
return 0;
-
}
工程管理(简单管理,日后还需深入学习makefile,以便进行高级的项目管理):
-
CC=gcc
-
-
target=main
-
-
CSOURCE:=
-
CSOURCE+=main.c
-
CSOURCE+=scan.c
-
-
CFLAGS:=
-
CFLAGS+=-Wall
-
-
$(target):$(CSOURCE)
-
$(CC) -o $@ $^ $(CFLAGS)
-
-
clean:
-
rm $(target)
运行结果:
总结:
实现了需要的功能。因为平时逻辑思维能力较差(脑子转不过来弯),所以在工作中遇到这类问题时往往反应迟钝,耽误大量宝贵时间。日后多加强这方面的练习,多做这种小练习,让大脑转动起来。
阅读(1720) | 评论(0) | 转发(0) |