Sort Lines in a Text File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Sort the Lines of a Text File in Alphabetical Order

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.

C program to sort the lines of a text file in alphabetical order using an array of strings, qsort, and strcmp, with step-by-step explanation.

šŸ“ 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:

  1. Open the file in read mode and count the lines (or just read into a dynamically growing array).
  2. Read each line into a dynamically allocated string with fgets() + strdup().
  3. Sort the array of pointers using qsort() with a comparator that wraps strcmp().
  4. Reopen the file in write mode (this truncates it) and write each sorted line back with fputs().
  5. 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:

Contents of colors.txt before: red
blue
green
yellow
orange
purple

Running the program:

Console: Enter the filename: colors.txt
Sorted 6 lines in 'colors.txt'.

After the program finishes, colors.txt contains:

Contents of colors.txt after: blue
green
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.
āš ļø Important: The program reopens the file in "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 with tolower before calling strcmp.
  • Numeric: Use atol/strtod to 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 strdup must have a matching free. Valgrind will report a leak on every line if you miss this.
  • Overwriting the input while reading: Never fopen the 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 dynamic realloc version here handles any number of lines (subject to memory).
  • Comparing with == instead of strcmp: Inside the comparator, you must call strcmp — comparing pointers gives wrong ordering.
  • Trailing newline issues: fgets keeps the \n in each line. strcmp will 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 == 0 explicitly, avoiding a qsort call with a NULL array.

šŸ’” Tips & Best Practices

  • If strdup gives 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 -g to catch type mismatches in the comparator signature.
  • Run under valgrind --leak-check=full to verify there are no leaks from the strdup calls.

šŸ“– Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 6. Delete a Specific Line from a Text File
  • 10. Replace a Word with Another Word in a Text File
  • 9. Merge Multiple Text Files into a Single Text File
  • 15. Copy the Contents of One Text File into Another
  • File Handling in C — Introduction
  • Files FAQ

Previous Problem: -->> 11. Encrypt the Contents of a Text File   ||   Next Problem: -->> 13. Decrypt the Contents of an Encrypted Text File

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.