ch8-fsize (Print file size)
Chapter_8 Exercise_8-4 | Exercise_8-5 |
fsize.c K&R, p. 181-182 download
#include <stdio.h> // for printf(), fprintf(), sprintf(), stderr, NULL
#include <string.h> // for strcmp(), strlen()
#include <sys/stat.h> // for struct stat, stat()
#include <sys/dir.h> // local directory structure, struct direct
#include <dirent.h> // for DIR, opendir(), readdir(), closedir()
void fsize(char *); // print file size
int main(int argc, char **argv) // print file sizes
{
if (argc == 1)
{fsize(".");} // default: current directory
else
{
while (--argc > 0) // all args but program name
{fsize(*++argv);} // skip program name
}
return 0;
}
void dirwalk(char *, void (*fcn)(char *));
void fsize(char *name) // print size of file "name"
{
struct stat stbuf;
if (stat(name, &stbuf) == -1)
{
fprintf(stderr, "fsize(): can't access %s\n", name);
return;
}
if ((stbuf.st_mode & S_IFMT) == S_IFDIR)
{dirwalk(name, fsize);}
printf("%8ld %s\n", stbuf.st_size, name);
}
#define MAX_PATH 1024
// apply fcn to all files in dir
void dirwalk(char *dir, void (*fcn)(char *))
{
char name[MAX_PATH];
struct direct *dp; // directory pointer
DIR *dfd; // directory file descriptor
if ((dfd = opendir(dir)) == NULL)
{
fprintf(stderr, "dirwalk(): can't open %s\n", dir);
return;
}
while ((dp = readdir(dfd)) != NULL)
{
if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
{continue;} // skip self and parent
if (strlen(dir)+strlen(dp->d_name)+2 > sizeof(name)) // MAX_PATH
{ // +2 for '/' and ending '\0'
fprintf(stderr, "dirwalk(): name %s/%s too long\n",
dir, dp->d_name);
return;
}
// else
sprintf(name, "%s/%s", dir, dp->d_name);
fcn(name); // (*fcn)(name);
}
closedir(dfd);
}
/*
gcc fsize.c -o fsize
./fsize
17248 ./fsize
1833 ./fsize.c
4096 .
./fsize .. // parent directory
*/
Chapter_8 Exercise_8-4 | BACK_TO_TOP | Exercise_8-5 |
Comments
Post a Comment