Advertisement
Guest User

Untitled

a guest
Jun 25th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.14 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <dirent.h>
  6.  
  7. char* txtOpen(char* txtName){
  8.     FILE* txt = fopen(txtName, "r");
  9.     if (txt == NULL){
  10.         printf("ERROR\n");
  11.     return NULL;
  12.     }
  13.     fseek(txt,0,SEEK_END);
  14.     int txtSize = ftell(txt);
  15.     fseek(txt,0,SEEK_SET);
  16.     if(txtSize == 0){
  17.     fclose(txt);
  18.         return NULL;
  19.     }
  20.     char* txtStr = (char*)malloc(sizeof(char)*10000);
  21.     fgets(txtStr, txtSize*sizeof(char),txt);
  22.     fclose(txt);
  23.     return txtStr;
  24. }
  25.  
  26. void list_dir(const char* dirName, char** strsTxt, int* len){
  27.     char current_path[10000];
  28.     strcpy(current_path, dirName);
  29.     DIR *current_dir = opendir(current_path);
  30.     if (current_dir == NULL) return;
  31.     struct dirent* current_dir_file =readdir(current_dir);
  32.     while(current_dir_file){
  33.         int path_len = strlen(current_path);
  34.     strcat(current_path, "/");
  35.     strcat(current_path, current_dir_file->d_name);
  36.         if(current_dir_file->d_type == DT_REG && strstr(current_dir_file->d_name, ".txt") != NULL){
  37.         if((strsTxt[*len] = (char*)txtOpen(current_path)) != NULL)
  38.         (*len)++;
  39.     }
  40.     if (current_dir_file->d_type == DT_DIR && strcmp(".", current_dir_file->d_name) != 0 && strcmp("..",current_dir_file->d_name) != 0) list_dir(current_path,strsTxt,len);
  41.     current_path[path_len] = '\0';
  42.     current_dir_file = readdir(current_dir);
  43.     }
  44.     closedir(current_dir);
  45. }
  46.  
  47. int compare(const void* a, const void* b){
  48.     int a_value = atoi(*(char**)a);
  49.     int b_value = atoi(*(char**)b);
  50.     if (a_value > b_value)
  51.         return 1;
  52.     if (a_value < b_value)
  53.         return -1;
  54.     return 0;
  55. }
  56.  
  57. int main(){
  58.     char** strs = (char**)malloc(sizeof(char*)*1000);
  59.     int len = 0;
  60.     int i=0;
  61.     char str[1000];
  62.     FILE* fo;
  63.     fo=fopen("fo","w");
  64.     list_dir(".",strs,&len);
  65.     qsort(strs, len, sizeof(char*), compare);
  66.     for (i=0;i<len;i++) fprintf(fo,"%s\n", strs[i]);
  67.     fclose(fo); //закрываем
  68.     fo=fopen("fo","r");
  69.     while (fgets(str, 1000, fo))
  70.       printf("%s", str);
  71.     fclose(fo);
  72.     for (i=0;i<len;i++) free(strs[i]);
  73.     free(strs);
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement