Advertisement
Guest User

File list in C

a guest
Mar 23rd, 2013
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.23 KB | None | 0 0
  1. Here's my program for files listing:
  2.  
  3.    #include <stdio.h>
  4.    #include <string.h>
  5.    #include <dirent.h>
  6.    #include <unistd.h>
  7.    #include <sys/stat.h>
  8.    
  9.    
  10.    int list_files(char *parentdir);
  11.    
  12.    int main()
  13.    {
  14.        char s[80];
  15.        
  16.        system("chcp 1251");
  17.        list_files("C:\\Documents and Settings\\user\\Desktop\\New Folder");
  18.        system("pause");
  19.        return 0;
  20.    }
  21.    
  22.    int list_files(char *parentdir)
  23.    {
  24.      int file_count = 0;
  25.      DIR *dir;
  26.      struct dirent *de = NULL;
  27.      char subdirs[1000][1000];
  28.      int isubdirs = 0;
  29.    
  30.      char rootdir[1000];
  31.      strcpy(rootdir, parentdir);
  32.    
  33.      FILE *fp = stdout;
  34.    
  35.    seek:
  36.      dir = opendir(rootdir);
  37.      if (!dir) {
  38.        printf("\nERROR: [ %s ]\n", rootdir);
  39.        perror("Couldn't opendir: ");
  40.      }
  41.      else {
  42.        de = readdir(dir);
  43.        if (!de) {
  44.          printf("\nERROR:[ %s ]\n", rootdir);
  45.          perror("Couldn't readdir ");
  46.          goto out;
  47.        }
  48.        if (strcmp(de->d_name, "..") != 0 && strcmp(de->d_name, ".") != 0) {
  49.          fprintf(fp, "%s\\%s\n", rootdir, de->d_name);
  50.          file_count++;
  51.        }
  52.        while ((de = readdir(dir)) != NULL)
  53.        {
  54.          if (!strcmp(de->d_name, "..") || !strcmp(de->d_name, "."))
  55.            continue;
  56.          fprintf(fp, "%s\\%s\n", rootdir, de->d_name);
  57.          int c = 0;
  58.          char *t = de->d_name;
  59.          file_count++;
  60.          char filepath[1000];
  61.          strcpy(filepath, rootdir);
  62.          strcat(filepath, "\\");
  63.          strcat(filepath, de->d_name);
  64.          struct stat s;
  65.          if (stat(filepath, &s) != 0) {
  66.            printf("%s: ", filepath);
  67.            perror("ERROR: stat:");
  68.          }
  69.          if (S_ISDIR(s.st_mode))
  70.          {
  71.            strcpy(subdirs[isubdirs], rootdir);
  72.            strcat(subdirs[isubdirs], "\\");
  73.            strcat(subdirs[isubdirs], de->d_name);
  74.             isubdirs++;
  75.          }
  76.        }
  77.        closedir(dir);
  78.        if (isubdirs > 0) {
  79.          strcpy(rootdir, subdirs[--isubdirs]);
  80.          goto seek;
  81.        }
  82.      }
  83.    out:
  84.    
  85.      fclose(fp);
  86.    
  87.      return file_count;
  88.    }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement