sysprog
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/dir.h>
#include <dirent.h>
#include <stdio.h>
#define DIRSIZE MAXNAMLEN
main(argc,argv)
int argc;
char *argv[];
{
DIR* dirfd;
struct dirent *dentry;
static char filename[DIRSIZE+1];
struct stat stbuf;
if((dirfd = opendir(argv[1]))==NULL || chdir(argv[1]) == -1)
{
perror(argv[1]);
exit(1);
}
while((dentry=readdir(dirfd))!=NULL)
{
if(dentry->d_ino == 0)
continue;
memcpy(filename, dentry->d_name,DIRSIZE);
if(stat(filename,&stbuf)== -1)
{
perror(filename);
break;
}
if((stbuf.st_mode&S_IFMT) == S_IFREG)
printf("%-14s %d\n", filename,stbuf.st_size);
else
printf("%-14s\n", filename);
}
}
------------------
main()
int argc;
char *argv[];
{
DIR *dirfd;
struct direct *dentry;
static char filename[DIRSIZE+1];
struct stat stbuf;
//현재 디렉토리를 연다. '.'는 현재 위치한 디렉토리를 나타낸다.
if((dirfd = opendir(".")) == NULL)
{
perror(".");
exit(1);
}
//위에서 연 디렉토리에 있는 파일 혹은 서브 디렉토리 엔트리를 읽어온다. 없으때까지
while((dentry = readdir(dirfd)) != NULL)
{
//d_ino == 0인 것은 잘못된거나, 시스템이 특정 목적으로 사용하는거 므로 건너 뛴다.
if(dentry->d_ino == 0)
continue;
//읽은 엔트리에서 이름을 복사한다.
memcpy(filename, dentry->d_name, DIRSIZE);
//파일 속성값을 가져온다
if(stat(filename, &stbuf) == -1)
{
perror(filename);
break;
}
//파일 속성인 파일이면 사이즈를 표시한다.
if((stbuf.st_mode & S_IFMT) == S_IFREG)
printf("%-14s %d\n", filename, stbuf.st_size);
else
printf("%-14s\n",filename);
}
}