title: C - Print Specific Line From Text File
body: <p>I'm new to programming so please be nice. </p>
  
  <p>Currently I'm trying to write a program that opens a text file, reads in two words, searches through the text file counts how many times the two words appear, and then finally prints the first line that the first word appeared on. </p>
  
  <p>So far this is what I have done: </p>
  
  <pre><code>#include &lt;stdio.h&gt; 
  #include &lt;string.h&gt; 
  #include &lt;stdlib.h&gt; 
  
  FILE *infile;
  char inputWord1[100], inputWord2[100], filename[100], wordInText[100], line[500]; 
  int i, count, strComp, word1Count, word2Count, wordLen, lineCount; 
  char c;
  
  int main() { 
      printf("Enter the first word: "); 
      gets(inputWord1); 
      printf("Enter the second word: "); 
      gets(inputWord2); 
      printf("Enter the file name: "); 
      gets(filename); 
  
      infile = fopen(filename, "r"); 
      if(infile == NULL) { 
          printf("Error"); 
          exit(1); 
      } 
  
      word1Count = 0; word2Count = 0; lineCount = 1;
      while(fscanf(infile, "%s", wordInText) != EOF) { 
          wordLen = strlen(wordInText);
          for(i = 0; i &lt; wordLen; i++) {
              if(wordInText[i] &gt;= 65 &amp;&amp; wordInText[i] &lt;= 90) { 
                  wordInText[i] = wordInText[i] + 32; 
              }
          }
  
          for(c = getc(infile); c != EOF; c = getc(infile)) {
              if(c == '\n') { 
                  lineCount = lineCount + 1;
              }
          }
  
          strComp = strcmp(wordInText, inputWord1); 
          if(strComp == 0) { 
              word1Count++;
              if(word1Count == 1) { 
                  for(int x = lineCount; x &lt;= lineCount; x++) {
                      fgets(line, 500, infile); 
                      printf("%s\n", line);
                  }
              }
          }
          strComp = strcmp(wordInText, inputWord2); 
          if(strComp == 0) { 
              word2Count++; 
          }
      }
      printf("Word 1 appears %d times\n", word1Count); 
      printf("Word 2 appears %d times\n", word2Count);
  }
  </code></pre>
  
  <p>So all this works except: </p>
  
  <pre><code>strComp = strcmp(wordInText, inputWord1); 
          if(strComp == 0) { 
              word1Count++;
              if(word1Count == 1) { 
                  for(int x = lineCount; x &lt;= lineCount; x++) {
                      fgets(line, 500, infile); 
                      printf("%s\n", line);
                  }
              }
          }
  </code></pre>
  
  <p>The last for loop isn't working properly. It prints out the \n but does not print the line. I really don't know why it's not working. All the other parts work fine. </p>
  
  <p>If anyone has any ideas on how to resolve this I would really appreciate it. Please keep in mind I only know basic C functions and I haven't completely finished this program (still need to convert entered words to lowercase).</p>