[ create a new paste ] login | about

Link: http://codepad.org/APIS2iA7    [ raw code | fork ]

C, pasted on Apr 30:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef LOOPCOUNT
#define LOOPCOUNT 1
#endif

char *read_file(char *fname)
{
    FILE *fp;
    size_t filesize;
    char *buff;

    fp = fopen(fname, "rb");
    fseek(fp, 0, SEEK_END);
    filesize = ftell(fp);
    buff = (char *)calloc(1, filesize + 1);
    buff[filesize] = '\0';
    fseek(fp, 0, SEEK_SET);
    fread(buff, filesize, 1, fp);
    fclose(fp);

    return buff;
}

char **search_pos(char **begin, char **end, char *word)
{
    if (begin == end) return begin;

    {
        int mid = (end - begin)/2;
        int diff = strcmp(*(begin + mid), word);
        if (diff > 0) {
            return search_pos(begin, begin + mid, word);
        } else if (diff == 0) {
            return begin + mid;
        } else {
            return search_pos(begin + mid + 1, end, word);
        }
    }
}

void task(char *fn, int is_asc)
{
    char *buff;
    char **index = 0;
    char **p;
    char *token;
    int count = 0;

    buff = read_file(fn);

    token = strtok(buff, "\n");
    while (token) {
        count++;
        index = (char **)realloc(index, count * sizeof(*index));
        index[count - 1] = 0;

        // for (p = index; p != index + count - 1 && strcmp(token, *p) > 0; p++) ;
        p = search_pos(index, index + count - 1, token);
        memmove(p + 1, p, (index + count - 1 - p) * sizeof(*p));
        *p = token;

        token = strtok(NULL, "\n");
    }

    }

    if (is_asc) {
        for (p = index; p < index + count; p++) {
            puts(*p);
        }
    } else {
        for (p = index + count - 1; p >= index; p--) {
            puts(*p);
        }
    }

    free(index);
    free(buff);
}

int main(int argc, char **argv)
{
    int is_asc = 1;

    if (argc != 2 && argc != 3) {
        fprintf(stderr, "USAGE: %s filename [desc]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    is_asc = !(argc == 3 && !strcmp(argv[2], "desc"));

    {
        int loopcount;
        for (loopcount=0; loopcount < LOOPCOUNT; loopcount++) {
            task(argv[1], is_asc);
        }
    }

    return 0;
}


Create a new paste based on this one


Comments: