In this tutorial, you'll learn how to sort the lines of a text file alphabetically using the C programming language. This is a from-scratch version of the Unix sort command. Because a file is a linear stream and you can't easily swap lines in place, the standard approach is to read every line into an in-memory array, sort the array with qsort() and strcmp(), then write the sorted lines back to the file. This is the same pattern you'd use to sort argv or any list of strings.
š Problem Statement
Write a program in C language to sort the lines of a text file in alphabetical order.
āļø How the Program Works
The program follows a read-sort-write pattern:
- Open the file in read mode and count the lines (or just read into a dynamically growing array).
- Read each line into a dynamically allocated string with
fgets()+strdup(). - Sort the array of pointers using
qsort()with a comparator that wrapsstrcmp(). - Reopen the file in write mode (this truncates it) and write each sorted line back with
fputs(). - Free every duplicated string and close the file.
š» Complete C Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 1024
/* qsort comparator: sort strings in ascending alphabetical order */
static int compare_strings(const void *a, const void *b)
{
const char *s1 = *(const char **)a;
const char *s2 = *(const char **)b;
return strcmp(s1, s2);
}
int main(void)
{
FILE *fp;
char filename[100];
char line[BUFSIZE];
char **lines = NULL;
size_t count = 0, capacity = 0;
size_t i;
printf("Enter the filename: ");
scanf("%99s", filename);
/* ---- Read all lines into memory ---- */
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: Could not open '%s'.\n", filename);
return 1;
}
while (fgets(line, BUFSIZE, fp) != NULL)
{
if (count == capacity)
{
size_t new_cap = (capacity == 0) ? 16 : capacity * 2;
char **tmp = realloc(lines, new_cap * sizeof(char *));
if (tmp == NULL)
{
printf("Error: Out of memory.\n");
for (i = 0; i < count; i++) free(lines[i]);
free(lines);
fclose(fp);
return 1;
}
lines = tmp;
capacity = new_cap;
}
lines[count] = strdup(line);
if (lines[count] == NULL)
{
printf("Error: Out of memory.\n");
for (i = 0; i < count; i++) free(lines[i]);
free(lines);
fclose(fp);
return 1;
}
count++;
}
fclose(fp);
if (count == 0)
{
printf("File is empty. Nothing to sort.\n");
free(lines);
return 0;
}
/* ---- Sort the array of strings ---- */
qsort(lines, count, sizeof(char *), compare_strings);
/* ---- Write the sorted lines back to the file ---- */
fp = fopen(filename, "w");
if (fp == NULL)
{
printf("Error: Could not reopen '%s' for writing.\n", filename);
for (i = 0; i < count; i++) free(lines[i]);
free(lines);
return 1;
}
for (i = 0; i < count; i++)
fputs(lines[i], fp);
fclose(fp);
/* ---- Free everything ---- */
for (i = 0; i < count; i++)
free(lines[i]);
free(lines);
printf("Sorted %zu lines in '%s'.\n", count, filename);
return 0;
}š„ļø Sample Output
Assume colors.txt contains the following lines, in non-alphabetical order:
colors.txt before:
redblue
green
yellow
orange
purple
Running the program:
Sorted 6 lines in 'colors.txt'.
After the program finishes, colors.txt contains:
colors.txt after:
bluegreen
orange
purple
red
yellow
š Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
#include <stdlib.h> |
Provides qsort, malloc, realloc, free, and strdup (with _GNU_SOURCE or _POSIX_C_SOURCE on strict ISO C compilers). |
char **lines |
An array of char *. Each element will point to a dynamically allocated copy of one line. This is the same structure as argv. |
realloc(lines, new_cap * sizeof(char *)) |
Grows the array geometrically (16 ā 32 ā 64 ā¦). This gives amortized O(1) appends instead of O(n²). |
strdup(line) |
Allocates a new buffer and copies line into it. The buffer is freed later. If strdup isn't available, use malloc + strcpy. |
qsort(lines, count, sizeof(char *), compare_strings) |
The generic sort from the standard library. It sorts an array of pointers using the comparator. |
compare_strings |
Casts each void * argument to const char **, dereferences to get the actual string, then calls strcmp. |
fopen(filename, "w") |
Reopens the file for writing ā this truncates the file, wiping the original content before we write the sorted version. |
fputs(lines[i], fp) |
Writes each sorted line back. fgets preserved the trailing newline, so fputs doesn't need to add one. |
free(lines[i]); free(lines); |
Frees every duplicated string and the array itself. Without this, the program leaks memory. |
"w" mode ā which truncates it. If the program crashes between the read and the write, the original content is lost. For a safer version, write to a temporary file and swap it in with remove() + rename() (see Problem 6 for the full pattern).
š§ How the Comparator Works
qsort is type-agnostic ā it takes void * pointers and only cares about their size. So the comparator receives two const void * pointers, each pointing to an element of the array. Since our array elements are char *, we must:
- Cast each argument to
const char **. - Dereference to get the actual
char *string. - Compare the two strings with
strcmp.
strcmp returns a negative number if s1 < s2, zero if equal, and a positive number if s1 > s2 ā exactly what qsort expects. If you forget the cast-and-dereference step and try to pass strcmp directly, the program will crash or produce garbage, because strcmp would treat a pointer-to-pointer as if it were a pointer-to-char.
š Sorting Options
The comparator is the only place where sort behavior lives. Swap it out to change the order:
- Descending: Return
strcmp(s2, s1)ā note the reversed argument order. - Case-insensitive: Use
strcasecmp(POSIX) or lowercase both strings withtolowerbefore callingstrcmp. - Numeric: Use
atol/strtodto convert and return the numeric difference. - By length: Return
strlen(s1) - strlen(s2). - By last word: Find the last space in each line, then compare the suffixes.
š Common Pitfalls
- Forgetting to free the duplicated strings: Every
strdupmust have a matchingfree. Valgrind will report a leak on every line if you miss this. - Overwriting the input while reading: Never
fopenthe same file in"w"mode before you've finished reading. Read first, close, then reopen for writing. - Using a plain
char *lines[N]: A fixed-size array limits how many lines the file can have. The dynamicreallocversion here handles any number of lines (subject to memory). - Comparing with
==instead ofstrcmp: Inside the comparator, you must callstrcmpā comparing pointers gives wrong ordering. - Trailing newline issues:
fgetskeeps the\nin each line.strcmpwill sort"cat\n"relative to"caterpillar\n"correctly because both have the newline. If you ever strip the newline from some lines but not others, the sort order becomes unpredictable. - Empty file: The program handles
count == 0explicitly, avoiding aqsortcall with a NULL array.
š” Tips & Best Practices
- If
strdupgives you portability headaches, define your own one-line helper:char *dup(const char *s) { char *p = malloc(strlen(s) + 1); if (p) strcpy(p, s); return p; }. - For files with more than a million lines, the in-memory approach still works on most machines (a few hundred MB), but you may want to stream into a temp file with an external merge sort for truly huge inputs.
- Use
gcc -Wall -Wextra -std=c11 -gto catch type mismatches in the comparator signature. - Run under
valgrind --leak-check=fullto verify there are no leaks from thestrdupcalls.