Search Suggest

Scanning Directories


Scan thư mục là một công việc cơ bản được thực hiện khi chúng ta mở  Window Explorer để duyệt thư mục. Trong lập trình hệ thống nhúng thường dùng scan khi bạn cắm USB vào.
Dưới đây là một số function được dùng:
+ opendir
+ readdir
+ telldir
+ seekdir
+ closedir

Cấu trúc chứa thông tin về file/directory được chứa trong các struct cung cấp bởi các thư viện stat.h và dirent.h.

1. opendir
 #include <sys/types.h>  
#include <dirent.h>
DIR *opendir(const char *name);

opendir mở thư mục và khởi tạo một directory stream.
+ name
Đường dẫn đến thư mục muốn mở.
+ return
Trả về con trỏ đến cấu trúc DIR, trả về NULL nếu lỗi.

2. readdir
 #include <sys/types.h>  
#include <dirent.h>
struct dirent *readdir(DIR *dirp);

readdir đọc thư mục.
+ dirp
Con trỏ DIR được trả về từ opendir.
+ return
Trả về con troe đến cấu trúc dirent diễn tả chi tiết về thư mục được đọc. Trả về NULL khi đọc hết thư mục hoặc có lỗi, errno lưu trữ mã lỗi.

struct dirent chứa hai trường cơ bản:
+ ino_t d_ino : The inode of the file
+ char d_name[] : The name of the file

3. telldir
 #include <sys/types.h>  
#include <dirent.h>
long int telldir(DIR *dirp);

telldir trả về vị trí hiện tại trong directory stream.

4. seekdir
 #include <sys/types.h>  
#include <dirent.h>
void seekdir(DIR *dirp, long int loc);

seekdir di chuyển vị trí của con trỏ directory stream.
+ dirp
Directory stream.
+ loc
Vị trí ofset so với vị trí hiện tại của con trỏ (có được từ telldir)

5. closedir
 #include <sys/types.h>  
#include <dirent.h>
int closedir(DIR *dirp);

Đóng directory stream.

Ex:
scandir.c
 #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);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {
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(int argc, char **argv)
{
if(argc != 2) return;
printf("Directory scan of %s:\n", argv[1]);
printdir(argv[1],0);
exit(0);
}


Compile & Execute:
 $ gcc scandir.c   
$ ./a.out /home/ninhld/Github/eslinuxprogramming
Directory scan of /home/ninhld/Github/eslinuxprogramming:
simple_read.c
gets.c
dup2.c
dup.c
chmod.c
lseek.c

Đăng nhận xét