Created
May 9, 2016 14:32
-
-
Save VOID001/b426d4b58d9cc963ac0961f671650f2c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************************************************* | |
> File Name: dir_walk_example.c | |
> Author: VOID_133 | |
> A small program demos the process "ls -R", potential buggy | |
> Mail: ################### | |
> Created Time: Mon 09 May 2016 09:24:56 PM CST | |
************************************************************************/ | |
#include<stdio.h> | |
#include<string.h> | |
#include<stdlib.h> | |
#include<unistd.h> | |
#include<sys/file.h> | |
#include<sys/types.h> | |
#include<sys/stat.h> | |
#include<dirent.h> | |
#include<fcntl.h> | |
#include<errno.h> | |
#define MAX_PATH 2048 | |
struct stat fs_stat; | |
void usage(); | |
void get_size(char *filename); | |
int main(int argc, char *argv[]) | |
{ | |
if(argc < 2) | |
{ | |
usage(); | |
} | |
else | |
{ | |
while(--argc > 0) | |
get_size(*++argv); | |
} | |
} | |
void dir_walk(char *dir, void (*fsz)(char *)) | |
{ | |
char file_name[MAX_PATH]; | |
DIR *dfd; | |
struct dirent* pentry; | |
printf("entering %s...\n", dir); | |
if((dfd = opendir(dir)) == NULL) | |
{ | |
perror("opendir"); | |
//exit(errno); | |
} | |
else | |
{ | |
while((pentry = readdir(dfd)) != NULL) | |
{ | |
if(!strcmp(pentry->d_name, ".") || !strcmp(pentry->d_name, "..")) | |
{ | |
printf("%8ld %s\n", 0, pentry->d_name); | |
continue; | |
} | |
if(strlen(dir) + strlen(pentry->d_name) + 2 > MAX_PATH) | |
{ | |
fprintf(stderr, "dir_walk name %s/%s is too long", dir, pentry->d_name); | |
} | |
if(!strcmp(dir,"/")) | |
sprintf(file_name, "/%s", pentry->d_name); | |
else | |
sprintf(file_name, "%s/%s", dir, pentry->d_name); | |
fsz(file_name); | |
} | |
closedir(dfd); | |
} | |
return ; | |
} | |
void get_size(char *file_name) | |
{ | |
int retval = 0xdeadbeef; | |
retval = lstat(file_name, &fs_stat); | |
if(retval < 0) | |
perror("stat"); | |
else | |
{ | |
mode_t mode = fs_stat.st_mode; | |
if(((mode & S_IFMT) == S_IFDIR) && ((mode & S_IFMT) != S_IFLNK)) | |
{ | |
dir_walk(file_name, get_size); | |
} | |
else | |
{ | |
printf("%8ld %s\n", fs_stat.st_size, file_name); | |
} | |
} | |
} | |
void usage() | |
{ | |
printf("Usage: myls directory_name\n"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment