Extraction of filenames with dirent
Could You tell me, how to put only filenames (without director开发者_StackOverflow中文版ies) into my vector within following code?:
int getDir (string dir, vector<string> &files)
{
DIR *dp;
struct dirent *dirp;
if ((dp = opendir(dir.c_str())) == NULL) {
cout << "Error (" << errno << ") with " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
cout << dirp << endl;
files.push_back(string(dirp->d_name));
}
closedir(dp);
return 0;
}
You can use stat()
, and check the st_mode
field with the S_ISDIR
macro.
Try with this:
struct stat eStat;
stat(dirp->d_name, &eStat);
if(S_ISDIR(eStat.st_mode))
printf("found directory %s\n", dirp->d_name);
Better to use S_ISREG in place of S_ISDIR
It depends on your OS. Under Linux, the dirent structure returned by readdir
looks like this:
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 */
};
so you can examine the d_type field to see if you have a directory or a file.
精彩评论