Advertisement
EBobkunov

alphabetical sorting from a file found somewhere on the internet

Mar 10th, 2023
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <windows.h>
  5.  
  6. int cmp_func(const void *a, const void *b){
  7.     return strcmp(*(char**)a, *(char**)b);
  8. }
  9.  
  10. int main(void){
  11.     FILE *f;
  12.     long num, i;
  13.     char **arr, buf[BUFSIZ], *p;
  14.  
  15.     SetConsoleCP(1251);
  16.     SetConsoleOutputCP(1251);
  17.  
  18.     printf("file name: ");
  19.     if ( ! fgets(buf, BUFSIZ, stdin) ){
  20.         fprintf(stderr, "read error!\n");
  21.         exit(1);
  22.     }
  23.     if ( p = strrchr(buf, '\n') )
  24.         *p = '\0';
  25.     if ( ! *buf ){
  26.         fprintf(stderr, "empty line!\n");
  27.         exit(1);
  28.     }
  29.     if ( ( f = fopen(buf, "r") ) == NULL ){
  30.         fprintf(stderr, "open file error!\n");
  31.         exit(1);
  32.     }
  33.  
  34.     arr = NULL;
  35.     num = 0;
  36.     while ( fgets(buf, BUFSIZ, f) ){
  37.         if ( p = strrchr(buf, '\n') )
  38.             *p = '\0';
  39.         if ( ! *buf )
  40.             continue;
  41.         if ( ( arr = realloc(arr, sizeof(char*) * (num + 1)) ) == NULL ){
  42.             fprintf(stderr, "memory error!\n");
  43.             fclose(f);
  44.             exit(1);
  45.         }
  46.         if ( ( arr[num++] = strdup(buf) ) == NULL ){
  47.             fprintf(stderr, "memory error!\n");
  48.             fclose(f);
  49.             exit(1);
  50.         }
  51.     }
  52.     fclose(f);
  53.  
  54.     printf("\nlines read from file:\n");
  55.     for ( i = 0; i < num; ++i )
  56.         printf("%s\n", arr[i]);
  57.  
  58.     qsort(arr, num, sizeof(char*), cmp_func);
  59.  
  60.     printf("\nsorted lines:\n");
  61.     for ( i = 0; i < num; ++i )
  62.         printf("%s\n", arr[i]);
  63.  
  64.     for ( i = 0; i < num; ++i )
  65.         free(arr[i]);
  66.     free(arr);
  67.  
  68.     exit(0);
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement