//mkdir 函數創建文件夾
#include <sys/stat.h> #include <sys/types.h> int mkdir(const char *pathname, mode_t mode);
//rmdir 刪除文件夾
#include <unistd.h> int rmdir(const char *pathname);
//dopendir/fdopendir //打開文件夾
DIR是一個結構體,是一個內部結構,用來存儲讀取文件夾的相關信息。
DIR *opendir(const char *name); DIR *fdopendir(int fd);
//readdir 讀文件夾
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supportedby all file system types */
char d_name[256]; /* filename */
};
readdir 每次返回一條記錄項。。DIR*指針指向下一條記錄項。
#include <sys/types.h> #include <dirent.h> void rewinddir(DIR *dirp);
把文件夾指針恢復到文件夾的起始位置。
//telldir函數
#include <dirent.h> long telldir(DIR *dirp);
函數返回值是為文件夾流的當前位置,表示文件夾文件距開頭的偏移量。
//seekdir
#include <dirent.h> void seekdir(DIR *dirp, long offset);seekdir表示設置文件流指針位置。
//closedir 關閉文件夾流
#include <sys/types.h> #include <dirent.h> int closedir(DIR *dirp);
使用遞歸來遍歷文件夾下的文件
#include<stdio.h>
#include <errno.h>
#include<stdlib.h>
#include<string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_PATH 512
void print_file_info(char *pathname);
void dir_order(char *pathname);
void dir_order(char *pathname)
{
DIR *dfd;
char name[MAX_PATH];
struct dirent *dp;
if ((dfd = opendir(pathname)) == NULL)
{
printf("dir_order: can't open %s\n %s", pathname,strerror(errno));
return;
}
while ((dp = readdir(dfd)) != NULL)
{
if (strncmp(dp->d_name, ".", 1) == 0)
continue; /* 跳過當前文件夾和上一層文件夾以及隱藏文件*/
if (strlen(pathname) + strlen(dp->d_name) + 2 > sizeof(name))
{
printf("dir_order: name %s %s too long\n", pathname, dp->d_name);
} else
{
memset(name, 0, sizeof(name));
sprintf(name, "%s/%s", pathname, dp->d_name);
print_file_info(name);
}
}
closedir(dfd);
}
void print_file_info(char *pathname)
{
struct stat filestat;
if (stat(pathname, &filestat) == -1)
{
printf("cannot access the file %s", pathname);
return;
}
if ((filestat.st_mode & S_IFMT) == S_IFDIR)
{
dir_order(pathname);
}
printf("%s %8ld\n", pathname, filestat.st_size);
}
int main(int argc, char *argv[])
{
if (argc == 1)
{
dir_order(".");
} else
{
dir_order(argv[1]);
}
return 0;
}
