Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <windows.h>
- int cmp_func(const void *a, const void *b){
- return strcmp(*(char**)a, *(char**)b);
- }
- int main(void){
- FILE *f;
- long num, i;
- char **arr, buf[BUFSIZ], *p;
- SetConsoleCP(1251);
- SetConsoleOutputCP(1251);
- printf("file name: ");
- if ( ! fgets(buf, BUFSIZ, stdin) ){
- fprintf(stderr, "read error!\n");
- exit(1);
- }
- if ( p = strrchr(buf, '\n') )
- *p = '\0';
- if ( ! *buf ){
- fprintf(stderr, "empty line!\n");
- exit(1);
- }
- if ( ( f = fopen(buf, "r") ) == NULL ){
- fprintf(stderr, "open file error!\n");
- exit(1);
- }
- arr = NULL;
- num = 0;
- while ( fgets(buf, BUFSIZ, f) ){
- if ( p = strrchr(buf, '\n') )
- *p = '\0';
- if ( ! *buf )
- continue;
- if ( ( arr = realloc(arr, sizeof(char*) * (num + 1)) ) == NULL ){
- fprintf(stderr, "memory error!\n");
- fclose(f);
- exit(1);
- }
- if ( ( arr[num++] = strdup(buf) ) == NULL ){
- fprintf(stderr, "memory error!\n");
- fclose(f);
- exit(1);
- }
- }
- fclose(f);
- printf("\nlines read from file:\n");
- for ( i = 0; i < num; ++i )
- printf("%s\n", arr[i]);
- qsort(arr, num, sizeof(char*), cmp_func);
- printf("\nsorted lines:\n");
- for ( i = 0; i < num; ++i )
- printf("%s\n", arr[i]);
- for ( i = 0; i < num; ++i )
- free(arr[i]);
- free(arr);
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement