visoft

Sortare fisier, mai elegant

Nov 15th, 2019
223
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5.  
  6. int cmpfunc (const void * a, const void * b) {
  7.     char* c1;
  8.     char* c2;
  9.     c1 = *(char**)a;
  10.     c2 = *(char**)b;
  11.     int rez=0;
  12.     rez = strcmp(c1, c2);
  13.     printf("%s %d %s\n", c1, rez, c2);
  14.     return rez;
  15. }
  16.  
  17. int main(){
  18.     FILE *f;
  19.     char* nume_fisier = "src/in.txt";
  20.     char* str;
  21.     f = fopen(nume_fisier, "r");
  22.     if (f == NULL){
  23.             printf("Could not open file %s",nume_fisier);
  24.             return -1;
  25.     }
  26.  
  27.     fseek(f, 0L, SEEK_END);
  28.     int file_length = ftell(f);
  29.     fseek(f, 0L, SEEK_SET);
  30.  
  31.     str = (char*)malloc((file_length +1) * sizeof(char));
  32.     memset(str, 0, (file_length +1) * sizeof(char));
  33.  
  34.     int no_read_characters;
  35.     no_read_characters = fread(str, sizeof(char), file_length, f);
  36.     printf("am citit %d caractere\n%s\n", no_read_characters, str);
  37.  
  38.     char* cuvinte[100];
  39.     int nr_cuvinte = 0;
  40.     char * token;
  41.     char* delimitatori = " \n?.!";
  42.     /* get the first token */
  43.     token = strtok(str, delimitatori);
  44.     /* walk through other tokens */
  45.     while( token != NULL ) {
  46.         cuvinte[nr_cuvinte] = token;
  47.         nr_cuvinte++;
  48.         token = strtok(NULL, delimitatori);
  49.     }
  50.  
  51.     printf("Nr cuvinte: %d\n", nr_cuvinte);
  52.  
  53.     qsort(cuvinte, nr_cuvinte, sizeof(char*), cmpfunc);
  54.  
  55.     printf("Cuvintele sunt: ");
  56.     for(int i=0; i < nr_cuvinte; i++){
  57.         printf("%s ", cuvinte[i]);
  58.     }
  59.  
  60.     fclose(f);
  61.     free(str);
  62.     printf("\ndone");
  63. }
RAW Paste Data