unix简单读取目录

一、简单读取名称:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

int main(int argc, char *argv[]){
  //定义了一个目录指针,和dirent结构体
DIR *dp;
struct dirent *dirp;

dp = opendir(argv[1]); //打开目录,失败时返回 NULL
while((dirp=readdir(dp))!=NULL){
printf("%s\n", dirp->d_name);
}
return 0;
}


二、关于 struct dirent 的其他成员:

 struct dirent
  {
    long d_ino; /* inode number 索引节点号 */
    off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
    unsigned short d_reclen; /* length of this d_name 文件名长 */
    unsigned char d_type; /* the type of d_name 文件类型 */
    char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */
  }

可进一步打印:

printf("%s %ld %d %zd %c\n", dirp->d_name, dirp->d_ino,
  dirp->d_off, dirp->d_reclen, dirp->d_type);






Stay hungry Stay foolish
原文地址:https://www.cnblogs.com/xiangzi888/p/2238774.html