[ Back to the overview Matrix ]

Test case : Sort 2 using ANSI/ISO C

Lines used: 61
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void process(FILE *fp);
void add(const char *line, char ***arr, size_t *cap, size_t *max);
int stcmp(const void *p, const void *q);

int main(int argc, char **argv)
{
    if (argc > 1) {
        FILE *fp = fopen(argv[1], "r");
        if (fp == NULL)
          return EXIT_FAILURE;
        process(fp);
        fclose(fp);
    }
    else {
        process(stdin);
    }
    return 0;
}


void process(FILE *fp)
{
    char **lines = NULL;
    size_t linecap = 0;
    size_t linemax = 0;
    char buffer[1000];
    size_t i;
    FILE *out = fopen("sorted.txt", "w");

    if (out == NULL) {
        puts("Can't open sorted.txt for output!");
        exit(EXIT_FAILURE);
    }

    while (fgets(buffer, sizeof buffer, fp) != NULL)
    {
        add(buffer, &lines, &linecap, &linemax);
    }

    qsort(lines, linemax, sizeof *lines, stcmp);

    for (i=0; i < linemax; ++i) {
        fputs(lines[i], out);
        free(lines[i]);
    }
    fclose(out);
}


void add(const char *line, char ***arr, size_t *cap, size_t *max)
{
    if (*max >= *cap) {
        void *tmp = realloc(*arr, sizeof(char*) * (2*(*cap)+1));
        if (tmp == NULL)
          exit(EXIT_FAILURE);
        *arr = tmp;
        *cap = 2 * (*cap) + 1;
    }
    (*arr)[*max] = malloc(strlen(line)+1);
    if ((*arr)[*max] == NULL)
      exit(EXIT_FAILURE);
    strcpy((*arr)[(*max)++], line);
}


int stcmp(const void *p, const void *q)
{
    return strcmp(*(char**)p, *(char**)q);
}
Contributed by Arthur J. O`Dwyer at andrew.cmu.edu