1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include "myHeader.h"
int list(char *directory, size_t sizeDir);
int main(void)
{
int end, error=0;
size_t sizeDir;
char directory[256];
sizeDir = sizeof directory;
do
{
printf ("Path or <enter> for exit: ");
fgets (directory, sizeof directory, stdin); /* -sh- we take the path */
fclean (directory, stdin);
end = (directory[0] == '\0');
if (!end)
{
error = list(directory, sizeDir);
switch(error)
{
case 0:
fprintf(stdout, "\nNo Error\n\n");
break;
case 1:
fprintf(stdout, "\n%s is unknown\n\n", directory);
break;
case 2:
fprintf(stdout, "\nInternal error\n\n");
break;
case 3:
fprintf(stdout, "\nInternal error\n\n");
break;
case 4:
fprintf(stdout, "\nError when reading %s\n\n", directory);
break;
}
}
}
while (!end); /* while end[0] != '\0' */
return 0;
}
int list(char *directory, size_t sizeDir)
{
char cwd[256] = "";
DIR *dir = NULL;
int err;
struct dirent *file = NULL;
struct stat infos;
if ((dir = opendir(directory)) == NULL)
{
return 4;
}
printf("FOLDER %s:\n", directory);
/* -tc- we memorise the current working directory */
if (getcwd(cwd, sizeof cwd) == NULL)
return 3;
if (chdir(directory) != 0)
return 2;
while ((file = readdir(dir)) != NULL)
{
err = stat(file->d_name, &infos);
if (strcmp(file->d_name, ".") && strcmp(file->d_name, ".."))
{
if (err == 0)
{
if (S_ISDIR (infos.st_mode))
{
printf("\n[Folder]\t%s\n", file->d_name);
}
else
{
printf("\n[File]\t%s\n", file->d_name);
}
}
else
{
chdir(cwd);
return 1;
}
}
}
/* -tc- we return the initial repertory */
chdir(cwd);
printf("\nEND OF THE FOLDER: %s\n", directory);
closedir(dir);
(void) sizeDir;
return 0;
} |