With this code I'm able to print recursively all files and subdirectories from a given path.
What I want is to ignore (not print) all the subdirectorynames, and only print the file names.
This is the code:
#include <stdio.h>
#include <dirent.h>
#include <string.h>
void listFilesRecursively(char *basePath)
{
char path[1000];
struct dirent *dp;
DIR *dir = opendir(basePath);
if (!dir)
return;
while ((dp = readdir(dir)) != NULL)
{
if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
{
strcpy(path, basePath);
strcat(path, "/");
strcat(path, dp->d_name);
listFilesRecursively(path);
printf("%s\n", path);
}
}
closedir(dir);
}
int main()
{
char path[100];
printf("Enter path to list files: ");
scanf("%s", path);
listFilesRecursively(path);
return 0;
}
There are macros that tells you what type of file it is:
S_ISREG(): regular fileS_ISDIR(): directory fileS_ISCHR(): character special fileS_ISBLK(): block special fileS_ISFIFO(): pipe or FIFO -S_ISLNK(): symbolicS_ISSOCK(): link socketFirst of all you can use one of the following functions to get informaration:
From the Advanced Programming in Unix Environment book:
You can try something like the following:
Historically, early versions of the UNIX System didn’t provide the
S_ISxxxmacros. Instead, we had to logicallyANDthest_modevalue with the maskS_IFMTand then compare the result with the constants whose names areS_IFxxx. Most systems define this mask and the related constants in the file .For example: