title: How to count the number of words per line in a text file in C
body: <p>I want to be able to read a file line by line and count how many words are in each line. This is what I have so far:</p>
  
  <pre><code>int countWords(char* filename)
  {
     int wordCount=0;
     int lineCount=0;
  
     FILE *ptr_file;
     char buf[1000];
     ptr_file = fopen(filename,"r");
  
     if (!ptr_file) {
       return 1;
     }
  
     while (fgets(buf,1000,ptr_file) != NULL) {
       int len = strlen(buf);
       for(int x=0; x&lt;len; x++) {
         if (buf[x]!=' ' &amp;&amp; buf[x+1]==' '){
           wordCount++;
         }
         else if (buf[x]=='\n') {
           lineCount++;
           printf("Line %d: %d words", lineCount, wordCount);
           wordCount=0;
         }
         printf("%d",wordCount);
       }
  
     }
  
     fclose(ptr_file);
  
     return 0;
  }
  </code></pre>
  
  <p>I'm pretty new at C so still getting used to the whole pointer thing. When I run this program I get no output. This is the sort of output I'm looking for:</p>
  
  <pre><code>Line 1: 3 words
  Line 2: 5 words
  ...
  </code></pre>