This proof of concept does what you need.
But it would be much easier to
$ sort file.txt
Disclaimer: This is my first post to stack overflow, so if I did something wrong please tell me. :)
Memory overhead of this is 8MiB(sizeof(char *) * 1024*1024). It also stores the full contents of the file in memory. Consuming approximately ~60Mib of RAM.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#define LINES_IN_FILE 32
int compare(const void *ap, const void *bp)
{
char **a = (char **)ap;
char **b = (char **)bp;
return strcmp(*a, *b);
}
int main(void)
{
FILE *in = fopen("text.txt", "r");
if (!in)
return 1;
char **pbuf, **buf;
pbuf = buf = malloc(sizeof (char *) * LINES_IN_FILE);
size_t count = 0, len = 0;
while (getline(pbuf, &len, in) != -1) {
pbuf++;
count++;
len = 0;
}
qsort(buf, count, sizeof(char *), compare);
/* cleanup and print or whatever */
return 0;
}
You can speed this up a bit by replacing the strcmp() function with tests to only compare the first bytes, i.e. if(*a[0] > *b[0]) ...