Using strcmp to sort a file alphabetically

Posted on 2009-04-17
Last Modified: 2012-05-06
I am trying to write a program in C where I need to use strcmp to sort a file (with names) alphabetically.  I'm not sure what I'm doing wrong.  Please advise.
#include <stdio.h>

#include <string.h> 


/* Function main begins program execution */ 


int main(void)


    char name [ 30 ]; /* character length is 30 */


    FILE *cfPtr; /* cfPtr = unsorted_file.txt pointer */


    /* fopen opens file; exits program if file can't be opened */

    if ( ( cfPtr = fopen( "family.txt", "r" ) ) == NULL ) {

        printf( "File could not be opened\n" );

    } /* End if */


    /* Read records from file */

    else {

		// printf( "The list before sorted alphabetically\n\n" );

		// printf( "%s\n", "Name:\n" );

        fscanf( cfPtr, "%s", name );


        /* While not end of file */

        while( !feof( cfPtr ) ) {

				printf( "%s\n", name );

                fscanf( cfPtr, "%s", name );

        } /* End while */



int i;  

int strncmp(const char *s1, const char *s2, int n)



	  while (( *s1 == *s2) && (*s1) && i < n)






	 if (i == n)

		 return 0;

	 else if ((*s1 == *s2) && (! *s2))

		 return 0;

	 else if (( *s1) && (! *s2))

		 return -1;

	 else if ((*s2) && (! *s1))

		 return 1;


		 return ((*s1 > *s2) ? -1: 1);

  //printf( "%s\n", "Name:\n", name );


//	int fclose(FILE *cfPtr ); /* fclose closes the file */

Open in new window

Question by:clscor2
    LVL 6

    Assisted Solution

    Use the quicksort algorithm using strncmp as the way to compare where a string is 'less' or 'more' than another.
    LVL 49

    Accepted Solution

    strncmp can only compare one string to another.  In order to sort the lines of a file, you will need to compare each string to every other one.
    The standard way to do this is to read all string into memory (typically eash string into an element of a string array), then sort them, then output the sorted results.  As segurah mentioned, the quicksort algorithm can sort the array for you.  See :
        qsort Run-Time Library Reference
    It's possible that this is a school excercise that does not allow the use of qsort or does not expect you to be able to use string arrays yet.  In that case, there is an alternative (though very ineffiecnet technique):
    Read the file multiple times....
    On the first pass, find the lowest string.  Output that.
    On the next pass find the string that is the next to the lowest value.  Output that..
    Repeat until you have output all of the strings..
    LVL 53

    Assisted Solution

    >> I'm not sure what I'm doing wrong.

    For one thing, all your current program does, is read the names from the file, and display them on standard output.

    Second, the standard <string.h> library already has an implementation for strncmp :


    So there's no reason to re-implement it.

    Now, your main is a good start. Don't forget to fclose the file at the end though, and to return an int from main at the end.

    What you'll need to add, is code that actually sorts the file contents. One approach would be to read the entire file in memory (an array of strings for example), and then use one of the basic sorting algorithms on that array to get it sorted in alphabetic order. Other approaches have been listed above.

    If you are not sure about what sorting algorithms exist, this wiki is a good starting point :



    Author Closing Comment

    Thank you for your input and assistance!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
    Read about how to choose the best possible content marketing agency to suit your needs. Content marketing has become an integral part of running a successful tech business, so it is wise to be informed.
    Video by: Grant
    The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
    The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now