開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- プログラミング言語: C
- Clang (コンパイラ)
プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第8章(UNIXシステム・インタフェース)、8.6(例 - ディレクトリのリスティング)、演習8-5を解いてみる。
その他参考書籍
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
演習 8-5.
コード
sample.c
#define NAME_MAX 14
typedef struct {
long ino;
char name[NAME_MAX + 1];
} Dirent;
#include <sys/dir.h>
char *name;
struct stat stbuf;
#define S_IFMT 0160000
#define S_IFDIR 0040000
#define S_IFCHR 0020000
#define S_IFBLK 0060000
#define S_IFREG 0100000
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
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 (*fcn)(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("%8lld %lld %d %ld %ld %ld %s\n",
stbuf.st_size, stbuf.st_ino, stbuf.st_nlink, stbuf.st_atime,
stbuf.st_mtime, stbuf.st_ctime, 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;
}
if (strlen(dir) + strlen(dp->name) + 2 > sizeof(name)) {
fprintf(stderr, "dirwalk: name %s/%s too long\n",
dir, dp->name);
} else {
sprintf(name, "%s/%s", dir, dp->name);
(*fcn)(name);
}
}
closedir(dfd);
}
入出力結果(Terminal)
$ ./a.out sample.c a.out
1758 54720833 1 1378795799 1378795771 1378795771 sample.c
9464 63827035 1 1378795799 1378795773 1378795773 a.out
$
0 コメント:
コメントを投稿