/* 最近要做简单的linux文件管理的功能,用到函数相继贴出来.很乱,待总结!*/
/*reference :http://www.lslnet.com/linux/dosc1/10/linux-154990.htm*/
/* dir.c */
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
extern int errno;
/*
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dir);
int closedir(DIR *dir);
*/
int main(int argc,char *argv[])
{
DIR *dir;
struct dirent *pdir;
struct stat st;
char buf[1024];
char c_type[6][9]={"普通文件","目录","连接","\0","其他格式","\0"};
int type;
int n;
if(argc>2)
{
printf("Usage: dir /path\n");
return 0;
}
if(argc==2)
strncpy(buf,argv[1],99);
else
strcpy(buf,".");
printf("%s\n\n",buf);
dir=opendir(buf);
if(dir==NULL)
{
printf("Can not open %s\n",buf);
return 0;
}
n = strlen(buf);
if (buf[n-1] != '/') {
strcat(buf, "/");
n++;
}
while((pdir=readdir(dir))!=NULL)
{
strcat(buf, pdir->d_name);
if(stat(buf,&st)==0)
{
if(st.st_mode&S_IFREG)
type=0;
else if(st.st_mode&S_IFDIR)
type=1;
else if(st.st_mode&S_IFLNK)
type=2;
else type=4;
printf("%-10s%-20s%7d\n",c_type[type],pdir->d_name,(int)st.st_size);
}
else
printf("%-20s%-10d%-10d\n",pdir->d_name,st.st_mode,errno);
bzero(&st,sizeof(struct stat));
buf[n]='\0';
}
closedir(dir);
return 0;