e); //成功返回指针,失败返回NULL
struct dirent *readdir(DIR *dirp); //成功返回指针,失败返回NULL
int closedir(DIR *dirp); //成功返回0,失败返回-1
/* On Linux, the dirent structure is defined as follows: */
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 supported by all file system types */
char d_name[256]; /* filename */
};
/* d_type value is defined as follows */
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.
目录操作示例代码:递归遍历目录,打印所有文件路径
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
void display_dir(char *dir_path)
{
DIR *dir_ptr;
int dir_len;
struct dirent *file_info;
char sub_dir[256];
if (dir_path == NULL)
{
return;
}
dir_ptr = opendir(dir_path);
dir_len = strlen(dir_path);
if (dir_path[dir_len - 1] == '/')
{
dir_path[dir_len - 1] = '\0'; //统一输出方式,避免出现dir//file.txt的现象
}
while (file_info = readdir(dir_ptr))
{
if (strcmp(file_info->d_name, ".") == 0 || strcmp(file_info->d_name, "..") == 0)
continue;
switch (file_info->d_type)
{
case DT_DIR:
sprintf(sub_dir, "%s/%s", dir_path, file_info->d_name);
display_dir(sub_dir);
break;
case DT_REG:
case DT_BLK:
case DT_CHR:
case DT_FIFO:
case DT_LNK:
printf("%s/%s\n", dir_path, file_info->d_name);
break;
default:
break;
}
}
closedir(dir_ptr);
}
int main(int argc, char *argv[])
{
display_dir(argv[1]);
return 0;
}