I am working with Linux system.
DIR *dir;
struct dirent *ent;
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
I get "."
, ".."
and some file names as a result. How can I get rid of "."
and ".."
? I need those file names for further process. What's the type of ent->d_name
?? Is it a string or char?
Read the man page of readdir, get 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 ent->d_name
is a char array. You could use it as a string, of course.
To get rid of "."
and ".."
:
while ((ent = readdir (dir)) != NULL) {
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0 )
printf ("%s\n", ent->d_name);
}
Update
The resulting ent
contains file names and file folder names. If folder names are not needed, it is better to check ent->d_type
field with if(ent->d_type == DT_DIR)
.
Use strcmp
:
while ((ent = readdir (dir)) != NULL) {
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0)
//printf ("%s\n", ent->d_name);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.