Testing if a Text File is Sorted

A very common task in my technical world is determining if a flat text file is sorted or not. There are several ways to do this but I generally use the previous line / current line approach. Suppose you have a text file of people’s names like:
One way to check if such a file is sorted first by last name and then by first name is:
static void IsFileSortedByLastAndThenFirst(string fileToExamine)
    FileStream ifs = new FileStream(fileToExamine, FileMode.Open);
    StreamReader sr = new StreamReader(ifs);
    string line = "";
    string[] tokens = null;
    string currLastName = "";
    string currFirstName = "";
    string prevLastName = "";
    string prevFirstName = "";
    long ctr = 0;
    line = sr.ReadLine(); ++ctr; // priming read
    tokens = line.Split(‘,’);
    prevLastName = tokens[0];
    prevFirstName = tokens[1];
    while ((line = sr.ReadLine()) != null)
      tokens = line.Split(‘,’);
      currLastName = tokens[0];
      currFirstName = tokens[1];
      if (currLastName.CompareTo(prevLastName) < 0) // currLastName < prevLastName
        Console.WriteLine("Not sorted by last name at " + ctr);
        // display ctr, currLastName, etc.
      else if (currLastName.CompareTo(prevLastName) == 0 && currFirstName.CompareTo(prevFirstName) < 0)
        Console.WriteLine("Not sorted by first name at " + ctr);
        // display ctr, currLastName, etc.
      prevLastName = currLastName;
      prevFirstName = currFirstName;
    } // while
    sr.Close(); ifs.Close();
    Console.WriteLine("Done checking sorting");
} // IsFileSortedByLastAndThenFirst()
I do a priming read of the first line of the file and assign the values there to the previous variables. Then I walk through the file grabbing current varaiables. I check to see if the current line is out of order relative to the previous line. At the bottom of the loop I update the previous variables and then at the top of the loop I get new current variables. A very fundamental testing technique.
This entry was posted in Software Test Automation. Bookmark the permalink.