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))
{
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,
(long)filestat.st_size,
ctime(&filestat.st_mtime));
}
closedir(folder);
return(0);
}
Notes
* Multiple solutions are possible for this code, so don't accept my solution as the best 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 23 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.
Copyright © 1997-2025 by QPBC.
All rights reserved
