问题
I have the following code in C:
DIR *mydir = opendir("/");
struct dirent *entry = NULL;
while((entry = readdir(mydir)))
{
printf("%s\n", entry->d_name);
//printf("%i\n", entry->d_type);
}
closedir(mydir);
It works and shows the files/folders in the location, correctly.
However, I want to tell if it is a folder or a file. How can I do this? I tried with d_type (as you can see on the code) but no success.
回答1:
Use stat():
struct stat st;
stat("nodename", &st);
int isDirectory = S_ISDIR(st.st_mode);
回答2:
You should use stat() function wich get you a stat structure.
struct stat s;
if( stat(path,&s) == 0 )
{
if( s.st_mode & S_IFDIR )
{
//it's a directory
}
else if( s.st_mode & S_IFREG )
{
//it's a file
}
else
{
//something else
}
}
else
{
//error
}
回答3:
You can use built in macros like this:
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main(void)
{
DIR *mydir = opendir(/);
struct dirent *entry = NULL;
struct stat buf;
while((entry = readdir(mydir)))
{
printf("%s\n", entry->d_name);
if (stat(entry, &buf))
{
perror("stat");
exit(-1);
}
if ( S_ISDIR(buf.st_mode) )
{
printf("%s is a directory\n", entry);
}
if ( S_ISREG(buf.st_mode) )
{
printf("%s is a regular file\n", entry);
}
}
closedir(mydir);
return 0;
}
See man 2 stat
in a shell for more information.
回答4:
This is system-specific and we cannot give a completely solid answer without knowing your OS and possibly other settings.
d_type in fact does work for at least some systems. Your code gives a useful answer on RedHat Linux with a value of 4 for directories, 8 for regular files, and other values for other file types. This is with a fix to the typo to surround the name / in the call to opendir with quotes.
来源:https://stackoverflow.com/questions/13868994/determine-file-folder-in-c