C and C++ gets the list of files in the directory
- 2020-04-02 02:12:48
- OfStack
1. Data structure
struct dirent
{
long d_ino;
off_t d_off;
unsigned short d_reclen;
unsigned char d_type;
char d_name [NAME_MAX+1];
}
struct __dirstream
{
void *__fd;
char *__data;
int __entry_data;
char *__ptr;
int __entry_ptr;
size_t __allocation;
size_t __size;
__libc_lock_define (, __lock)
};
typedef struct __dirstream DIR;
2. Sample program
Where the program does not support the file type (d_type) in win, you can judge the file type according to the suffix of the file name; Linux can use d_type directly to determine whether it is a directory or a file.
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
int main(){
DIR *dir;
struct dirent *ptr;
dir = opendir("."); ///open the dir
while((ptr = readdir(dir)) != NULL) ///read the list of this dir
{
#ifdef _WIN32
printf("d_name: %sn", ptr->d_name);
#endif
#ifdef __linux
printf("d_type:%d d_name: %sn", ptr->d_type,ptr->d_name);
#endif
}
closedir(dir);
return 0;
}
Program output:
< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201402/20140227100543.jpg? 201412710648 ">