不浮躁
分类: 嵌入式
2015-07-26 21:53:23
原文地址:用文件IO操作实现ls命令 作者:xutianxi
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define N 256
void DisplayFile(struct stat buf, char fname[])
{
int n;
struct tm *tp;
switch (buf.st_mode & S_IFMT)
{
case S_IFREG:
printf("-");
break;
case S_IFDIR:
printf("d");
break;
case S_IFSOCK:
printf("s");
break;
case S_IFLNK:
printf("l");
break;
case S_IFBLK:
printf("b");
break;
case S_IFCHR:
printf("c");
break;
case S_IFIFO:
printf("p");
break;
}
for (n=8; n>=0; n--)
{
if (buf.st_mode & (1<
switch (n % 3)
{
case 2 :
printf("r");
break;
case 1 :
printf("w");
break;
case 0:
printf("x");
break;
}
}
else
{
printf("-");
}
}
printf(" %u ", buf.st_nlink);
printf("%s ", getpwuid(buf.st_uid)->pw_name);
printf("%s ", getgrgid(buf.st_gid)->gr_name);
printf("%ld", buf.st_size);
tp = localtime(&buf.st_mtime);
printf(" %d-%d-%d %d:%d ", tp->tm_year+1900, tp->tm_mon+1,
tp->tm_mday, tp->tm_hour, tp->tm_min);
printf("%s\n", fname);
return ;
}
void DisplayDir(char fname[])
{
DIR *mydir;
struct dirent *myitem;
char dirname[N];
struct stat buf;
if ((mydir = opendir(fname)) == NULL)
{
perror("fail to opendir");
return;
}
while ((myitem = readdir(mydir)) != NULL)
{
if (myitem->d_name[0] == '.') continue;
strcpy(dirname, fname);
strcat(dirname, "/");
strcat(dirname, myitem->d_name);
//printf("%s\n", dirname);
stat(dirname, &buf);
DisplayFile(buf, myitem->d_name);
}
closedir(mydir);
}
int main(int argc, char *argv[])
{
struct stat buf;
char fname[N];
if (argc < 2)
{
printf("Usage : %s
return -1;
}
if (stat(argv[1], &buf) < 0)
{
perror("fail to stat");
return -1;
}
strcpy(fname, argv[1]);
if ( S_ISDIR(buf.st_mode) )
{
DisplayDir(fname);
}
else
{
DisplayFile(buf, fname);
}
return 0;
}