dclean/iodir.c

101 lines
2.0 KiB
C
Executable File

#include "dclean.h"
struct dirent *dptr;
void list_directory(char *path, char *filename)
{
struct stat st, sb;
DIR *dirp;
int n, fd;
int out = open(filename, O_RDWR | O_CREAT, 0644); // opens file; creates it if it does not exist;
if (out < 0)
{ // error check
fprintf(stderr, "cannot open %s because of %s\n", filename, strerror(5));
exit(EXIT_FAILURE);
}
if ((dirp = opendir(path)) == NULL)
{
fprintf(stderr, "Opening %s : ", path);
perror("opendir:");
return;
}
while ((dptr = readdir(dirp)))
{
char *name = dptr->d_name;
stat(name, &sb);
if ((strcmp(name, "..") != 0) & (strcmp(name, ".") != 0))
{
#ifdef DEBUG
printf("st.st_mode : %d\n", st.st_mode);
#endif
if ((sb.st_mode & S_IFMT) == S_IFDIR)
{
char *p;
#ifdef DEBUG
printf("%s/%s/\n", path, name); // uncomment if you want to see the directory name.
#endif
p = malloc(strlen(name) + strlen(path) + 1 + 1);
strcpy(p, path);
strcat(p, "/");
strcat(p, name);
list_directory(p, filename);
free(p);
}
else if ((sb.st_mode & S_IFMT) == S_IFREG)
{
char *full;
full = malloc(strlen(path) + 1 + strlen(name) + 1);
strcpy(full, path);
strcat(full, "/");
strcat(full, name);
fd = open(full, O_RDONLY);
if (fd < 0)
{
fprintf(stderr, "unable to open file:%s\n", full);
perror("open:");
}
else
{
stat(full, &st);
#ifdef DEBUG
printf("%s %lld\n", full, st.st_size);
#endif
char number[50] = {};
sprintf(number, "%lld", st.st_size);
;
n = write(out, number, strlen(number));
n = write(out, "*", strlen("*"));
n = write(out, full, strlen(full)); // write the record descriptor
n = write(out, "\n", strlen("\n"));
if (n < 0)
{
fprintf(stderr, "%s\n", strerror(EIO));
exit(EXIT_FAILURE);
}; // error checking
}
close(fd);
free(full);
}
#ifdef DEBUG
else
printf("---> Not a regular file %s/%s\n", path, name);
#endif
}
}
closedir(dirp);
}
int main(int argc, char *argv[])
{
list_directory(argv[1], argv[2]);
}