title: Longest and Shortest word in a file C programming
body: <p>Hello and good evening,</p>
  
  <p>So i'm writing a program in C, that will accept a file.txt as an input and read the text.  The program should read the text file, find the longest and shortest word within the file, and print them out when it reaches the end.  </p>
  
  <p>I'm REALLY close but i'm getting a seg fault and, not only do I not know why, but i'm at a loss as to how to fix it.  </p>
  
  <p>Here's the code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  FILE *fp;
  char str[60];
  char *largest;
  char *smallest;
  char *word;
  int i, j;
  
  int main (int argc, char **argv) {
  
  // check that there are only two arguments
  if (argc == 2) {
      fp = fopen(argv[1], "r");
  }
  // if not throw this error
  else {
      perror("Argument error.");
      return (-1);
  }
  // check if the file exists
  if  (fp == NULL) {
      perror("Error opening file.");
      return (-1);
  }
  
  // set largest to first string and smallest to second
  largest = strcpy(largest, strtok(str, " "));
  smallest = strcpy(smallest, strtok(NULL, " "));
  word = strcpy(word, strtok(str, " "));
  
  // while we get lines of the file
  while (fgets (str, 60, fp) != NULL) {
      // while the token string isn't empty
      while (word != NULL) {
          if (strlen(largest) &gt; strlen(word)) {
              strcpy(word, largest);
          }
          if (strlen(smallest) &lt; strlen(word)) {
              strcpy(word, smallest);
          }
      }
  }
  printf("The largest word in the file is: %s", largest);
  printf("The smallest word in the file is: %s", smallest);
  
  fclose(fp);
  
  return 0;
  }
  </code></pre>
  
  <p>I'm pretty sure it's the second while loop...I don't want to use it anyway, but i've been hacking at this for so long it's all my logic can think of.  </p>
  
  <p>Any help would be appreciated.  This IS homework, though only a small part of it, and i'm not asking for helping solving the entire problem.  </p>
  
  <p>Also, there is a Makefile involved...I don't think it's important post but feel free to ask me and i'll update. </p>
  
  <p>As I built this I can confirm that the file is able to read and I can print, put, and do all kinds of cool things.  It only broke when I tried to implement my logic for longest/shortest word.</p>
  
  <p>Thanks!  </p>