Solution for Exercise 23-4
ex2304
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <time.h>
#include <sys/stat.h>
int main()
{
DIR *folder;
struct dirent *file;
struct stat filestat;
folder=opendir(".");
if(folder==NULL)
{
puts("Unable to read directory");
exit(1);
}
while( (file = readdir(folder)) != NULL )
{
stat(file->d_name,&filestat);
if( S_ISDIR(filestat.st_mode) )
{
printf("%-14s %-5s %s",
file->d_name,
"<DIR>",
ctime(&filestat.st_mtime));
}
else
{
printf("%-14s %5ld %s",
file->d_name,
filestat.st_size,
ctime(&filestat.st_mtime));
}
}
closedir(folder);
return(0);
}
Output
. <DIR> Thu May 21 21:27:11 2020
.. <DIR> Thu May 21 15:08:14 2020
listing2305.c 355 Thu May 21 15:36:29 2020
ex2303.c 564 Thu May 21 21:27:10 2020
listing2301.c 350 Thu May 21 15:32:52 2020
listing2306.c 222 Thu May 21 15:37:01 2020
listing2302.c 558 Thu May 21 21:22:12 2020
ex2301.c 350 Thu May 21 20:49:38 2020
a.out 12924 Thu May 21 21:27:11 2020
listing2303.c 357 Thu May 21 15:34:55 2020
ex2302.c 360 Thu May 21 20:57:01 2020
listing2304.c 381 Thu May 21 15:35:48 2020
ex2304.c 692 Thu May 21 21:41:21 2020
Notes
* Multiple solutions are possible for this code, so don't accept my solution as the only one!
* I put the the S_ISDIR macro to work at Line 22. The if condition returns TRUE if a directory is found, so I stuffed the printf() function that follows at Line 24 with the text <DIR> inside as an immediate value. Otherwise, the else part of the decision is executed, which looks similar to the code from Exercise 23-3.
* You can read more about file permissions and the related defined constants and macros in my blog series on file permissions here.
Copyright © 1997-2026 by QPBC.
All rights reserved
