Investigating the contents of a directory
We now know how to open a directory for reading,
and to determine the names of all items in that directory.
What is each "thing" found in the directory -
is it a directory, is it a file...?
To answer those questions,
we need to employ the POSIX function,
stat(),
to determine the attributes
of the items we find in directories:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <dirent.h>
#include <unistd.h>
void list_directory(char *dirname)
{
char fullpath[MAXPATHLEN];
.....
while((dp = readdir(dirp)) != NULL) {
struct stat stat_buffer;
sprintf(fullpath, "%s/%s", dirname, dp->d_name );
if(stat(fullpath, &stat_buffer) != 0) {
perror( progname );
}
else if( S_ISDIR( stat_buffer.st_mode )) {
printf( "%s is a directory\n", fullpath );
}
else if( S_ISREG( stat_buffer.st_mode )) {
printf( "%s is a regular file\n", fullpath );
}
else {
printf( "%s is unknown!\n", fullpath );
}
}
closedir(dirp);
}
|
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <dirent.h>
#include <unistd.h>
void list_directory(char *dirname)
{
char fullpath[MAXPATHLEN];
.....
while((dp = readdir(dirp)) != NULL) {
struct stat stat_buffer;
struct stat *pointer = &stat_buffer;
sprintf(fullpath, "%s/%s", dirname, dp->d_name );
if(stat(fullpath, pointer) != 0) {
perror( progname );
}
else if( S_ISDIR( pointer->st_mode )) {
printf( "%s is a directory\n", fullpath );
}
else if( S_ISREG( pointer->st_mode )) {
printf( "%s is a regular file\n", fullpath );
}
else {
printf( "%s is unknown!\n", fullpath );
}
}
closedir(dirp);
}
|
|
CITS2002 Systems Programming, Lecture 16, p7, 19th September 2023.
|