title: How to compare 2 files lexicographically using C
body: <p>Hey guys, I'm currently trying to implement a function using C that takes in two file names as command line arguments and compare them lexicographically.</p>
  
  <p>The function will return -1 if the contents of the first file are less than the contents of the second file, 1 if the contents of the second file are less than the contents of the first file, and 0 if the files are identical.</p>
  
  <p>Please give me some advice on how I should start with this.</p>
  
  <p>[EDIT]</p>
  
  <p>Hey guys sorry if there's any unclear part in the question, so I'll just post the link to the question here: <a href="http://undergraduate.csse.uwa.edu.au/units/CITS1210/Tutorials/tutorial03.html" rel="nofollow">Original question</a>. Thing is it's an uni assignment so we're expected to do it using only basic C properties, probably only including stdio.h, stdlib.h, and string.h. Sorry for the trouble caused. Also here's the code I already have, my main problem now is that the function doesn't know that file1.txt (refer to the link) has it's first line longer than file2.txt, but is actually lexicographically less:</p>
  
  <pre><code>int filecmp(char firstFile[], char secondFile[])
  {
      int similarity = 0;
      FILE *file1 = fopen(firstFile, "r");
      FILE *file2 = fopen(secondFile, "r");
      char line1[BUFSIZ];
      char line2[BUFSIZ];
  
      while (similarity == 0)
      {
          if (fgets(line1, sizeof line1, file1) != NULL)
          {
              if (fgets(line2, sizeof line2, file2) != NULL)
              {
                  int length;
  
                  if (strlen(line1) &gt; strlen(line2))
                  {
                      length = strlen(line1);
                  }
                  else
                  {
                      length = strlen(line2);
                  }
  
                  for (int i = 0; i &lt; length; i++)
                  {
                      if (line1[i] &lt; line2[i]) similarity = -1;
                      if (line1[i] &gt; line2[i]) similarity = 1;
                  }
              }
              else
              {
                  similarity = 1; //As file2 is empty
              }
          }
          else
          {
              if (fgets(line2, sizeof line2, file2) != NULL)
              {
                  similarity = -1; // As file1 is empty
              }
              else break;
          }
      }
  
      fclose(file1);
      fclose(file2);
  
      return similarity;
  }
  </code></pre>
  
  <p>[END EDIT]</p>
  
  <p>Many thanks,<br>
  Jonathan Chua</p>