#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
typedef struct Stack_S
{
char *filename;
struct Stack_S *next;
}ST_Stack_N;
typedef struct Stack_H_S
{
int N;
ST_Stack_N *top;
}ST_Head_S;
ST_Head_S g_StackHead;
ST_Stack_N *TraverDirPop(void)
{
ST_Stack_N *temp;
if(g_StackHead.N <= 0)
{
return NULL;
}
temp = g_StackHead.top;
g_StackHead.top = temp->next;
g_StackHead.N--;
temp->next = NULL;
return temp;
}
int TraverDirPush(const char *filename)
{
int len;
ST_Stack_N *pNewStack;
if(NULL == filename)
{
printf("filename is NULL\r\n");
return 0;
}
len = strlen(filename);
pNewStack = (ST_Stack_N *)malloc(sizeof(ST_Stack_N));
pNewStack->filename = (char *)malloc(len+1);
memset(pNewStack->filename, 0, len+1);
memcpy(pNewStack->filename, filename, len);
pNewStack->next = g_StackHead.top;
g_StackHead.top = pNewStack;
g_StackHead.N++;
return 0;
}
int InitStackHead(void)
{
g_StackHead.N = 0;
g_StackHead.top = NULL;
return 0;
}
void DeleteStrRepeatChar(char *str, char ch)
{
int sloop = 0, dloop = 0;
while('\0' != str[sloop])
{
if(ch == str[sloop] && str[sloop] == str[sloop -1])
{
sloop++;
}
else
{
str[dloop++] = str[sloop++];
}
}
str[dloop] = '\0';
}
int Traversal(const char *pathname)
{
int count = 0;
DIR *pDir;
char *pFullPath;
ST_Stack_N *temp;
struct dirent *pDirent;
struct stat buf;
pFullPath = (char *)malloc(PATH_MAX+1);
memset(pFullPath, 0, PATH_MAX+1);
lstat(pathname, &buf);
if(S_ISDIR(buf.st_mode))
{
TraverDirPush(pathname);
}
else
{
printf("the filename is not dir:%s\r\n", pathname);
return 0;
}
while(NULL != (temp = TraverDirPop()))
{
pDir = opendir(temp->filename);
if(NULL == pDir)
{
printf("open dir fail\r\n");
break;
}
count = 0;
printf("%s :\r\n", temp->filename);
while(NULL != (pDirent = readdir(pDir)))
{
if(!strcmp(pDirent->d_name, ".") || !strcmp(pDirent->d_name, ".."))
{
continue;
}
sprintf(pFullPath, "%s/%s", temp->filename, pDirent->d_name);
DeleteStrRepeatChar(pFullPath, '/');
if(lstat(pFullPath, &buf) < 0)
{
printf("read file info fail %s\r\n", pFullPath);
continue;
}
if(S_ISDIR(buf.st_mode))
{
TraverDirPush(pFullPath);
printf("%s\t", pFullPath);
}
else
{
printf("%s\t", pDirent->d_name);
}
count = ++count%5;
if(0 == count)
{
printf("\n");
}
}
printf("\n");
if(0 != count)
{
printf("\n");
}
free(temp->filename);
free(temp);
temp = NULL;
}
free(pFullPath);
return 0;
}
int main(int argc, char *argv[])
{
InitStackHead();
if(argc != 2)
{
printf("not start pathname\n");
return 0;
}
Traversal(argv[1]);
return 0;
}
linux遍历目录及文件
最新推荐文章于 2024-03-20 08:07:34 发布