#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int read(int fd, char *buf, int n);
int write(int fd, char *buf, int n);
int fstat(int fd, struct stat *st);
#define NAME_MAX 14
typedef struct {
long ino;
char name[NAME_MAX + 1];
} Dirent;
typedef struct {
int fd;
Dirent d;
} DIR;
DIR *opendir(char *);
Dirent *readdir(DIR *);
void closedir(DIR *);
void fsize(char *);
int main(int argc, char *argv[])
{
if (argc == 1)
fsize(".");
else
while (--argc > 0)
fsize(*++argv);
return 0;
}
void dirwalk(char *, void (*)(char *));
void fsize(char *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
void dirwalk(char *dir, void (*fcn)(char *))
{
char name[MAX_PATH];
Dirent *dp;
DIR *dfd;
if ((dfd = opendir(dir)) == NULL) {
fprintf(stderr
, "dirwalk: can't open %s\n", dir
); return;
}
while ((dp = readdir(dfd)) != NULL) {
if (strcmp(dp
->name
, ".") == 0 || strcmp(dp
->name
, "..") == 0) continue;
fprintf(stderr
, "dirwalk: name %s/%s too long\n", dir
, dp
->name
); else {
sprintf(name
, "%s/%s", dir
, dp
->name
); (*fcn)(name);
}
}
closedir(dfd);
}
DIR *opendir(char *dirname)
{
int fd;
struct stat stbuf;
DIR *dp;
if ((fd = open(dirname, O_RDONLY, 0)) == -1
|| fstat(fd, &stbuf) == -1
|| (stbuf.st_mode & S_IFMT) != S_IFDIR
|| (dp
= malloc(sizeof(DIR
))) == NULL
) return NULL;
dp->fd = fd;
return dp;
}
void closedir(DIR *dp)
{
if(dp) {
close(dp->fd);
}
}
#define DIRSIZ 14
struct direct
{
ino_t d_ino;
char d_name[DIRSIZ];
};
Dirent *readdir(DIR *dp)
{
struct direct dirbuf;
static Dirent d;
while ((read(dp->fd, (char *) &dirbuf, sizeof(dirbuf))) != EOF) {
if (dirbuf.d_ino == 0) {
continue;
}
d.ino = dirbuf.d_ino;
strncpy(d.
name, dirbuf.
d_name, DIRSIZ
); d.name[DIRSIZ] = '\0';
return &d;
}
return NULL;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPHN0cmluZy5oPgojaW5jbHVkZSA8ZmNudGwuaD4KI2luY2x1ZGUgPHN5cy90eXBlcy5oPgojaW5jbHVkZSA8c3lzL3N0YXQuaD4KCmludCByZWFkKGludCBmZCwgY2hhciAqYnVmLCBpbnQgbik7CmludCB3cml0ZShpbnQgZmQsIGNoYXIgKmJ1ZiwgaW50IG4pOwppbnQgZnN0YXQoaW50IGZkLCBzdHJ1Y3Qgc3RhdCAqc3QpOwoKI2RlZmluZSBOQU1FX01BWCAxNAoKdHlwZWRlZiBzdHJ1Y3QgewogICAgbG9uZyBpbm87CiAgICBjaGFyIG5hbWVbTkFNRV9NQVggKyAxXTsKfSBEaXJlbnQ7Cgp0eXBlZGVmIHN0cnVjdCB7CiAgICBpbnQgZmQ7CiAgICBEaXJlbnQgZDsKfSBESVI7CgpESVIgKm9wZW5kaXIoY2hhciAqKTsKRGlyZW50ICpyZWFkZGlyKERJUiAqKTsKdm9pZCBjbG9zZWRpcihESVIgKik7Cgp2b2lkIGZzaXplKGNoYXIgKik7CgppbnQgbWFpbihpbnQgYXJnYywgY2hhciAqYXJndltdKQp7CiAgICBpZiAoYXJnYyA9PSAxKQogICAgICAgIGZzaXplKCIuIik7CiAgICBlbHNlCiAgICAgICAgd2hpbGUgKC0tYXJnYyA+IDApCiAgICAgICAgICAgIGZzaXplKCorK2FyZ3YpOwogICAgcmV0dXJuIDA7Cn0KCnZvaWQgZGlyd2FsayhjaGFyICosIHZvaWQgKCopKGNoYXIgKikpOwoKdm9pZCBmc2l6ZShjaGFyICpuYW1lKQp7CiAgICBzdHJ1Y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