Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to traverse the files in the directory in C++

Shulou Source: shulou.com Published: 2022-06-02 05:27:28 11月12日 Update

This article introduces how to traverse the files under the directory in C++. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

Code first:

# include

# include

Void print_dir (DIR * dir) {

Struct dirent * file

/ / iterate through the contents of the folder

While ((file = readdir (dir))! = NULL) {

Printf ("File location =% ld", telldir (dir))

Printf ("child files:% 20s", file- > d_name)

Printf ("\ n")

}

}

Int main (int argc, const char * argv []) {

Const char * dirPATH = "/ Users/ckend/Documents"

DIR * dir = opendir (dirPATH)

Print_dir (dir)

Return 0

}

The header file you need to use: "dirent.h"

Structure and function to be used: "struct dirent"

"readdir ()"

"opendir ()"

"telldir ()"

Explain it one by one:

Dirent.h, which contains many header files about the functions or structures of directory operations.

Readdir (), from dirent.h, the statement in the program:

While ((file = readdir (dir))! = NULL) {}

Its function is to return a dirent structure pointer to the files in the folder, which checks one by one until there are no more files and NULL is returned.

Opendir (), also from dirent.h, is used to open a folder path and return the DIR* pointer to that folder.

Telldir (), also from dirent.h, gets the current pointer position and returns it.

Struct dirent, this structure also comes from dirent. Its contents are as follows (excerpted from references):

Struct dirent {ino_t diterino; / * inode number * / off_t dailseekoff in the file system; / * related to the location pointer operation of the folder stream * / unsigned short dumbrecline; / * the data length of this record * / unsigned char d_type / * the file types of the current traversal subitems: files, folders, link, socket, etc. * / char d_name [256]; / * the file names of the current traversal subitems * /}. This is the end of how to traverse the files in the directory in C++. I hope the above can be helpful and learn more. If you think the article is good, you can share it for more people to see.

Tags: Files folders locations contents pointers structures directories more caterpillars functions subitems references help yes previous generations functions interests references boys buddies Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Redmi NVidia Linux macOS