title: reading CSV in C when the table is broken
body: <p>here is my C code to read CSV file:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  struct record
  {long a,b,c;    };
  
  int main(void)
  {
      const char filename[] = "b.csv";
      FILE *file = fopen(filename, "r");
  
      if ( file != NULL )
      {
          char line [ 80 ];
          struct record record [ 50 ];
          size_t count, i = 0;
  
          while ( i &lt; sizeof record / sizeof *record )
          {
              if ( fgets(line, sizeof line, file) == NULL )
              {
                  break;
              }
  
              if ( sscanf(line, "%ld,%ld,%ld", &amp;record[i].a,&amp;record[i].b,&amp;record[i].c) == 3 )
              {
                  ++i;
              }
          }
          fclose(file);
  
          for ( count = i, i = 0; i &lt; count; ++i )
          {
              printf("record[%lu]: a = %ld b = %ld c = %ld\n",
                  (long unsigned)i, record[i].a, record[i].b,record[i].c);
              }
      }
      else
      {
          perror(filename);
      }
      return 0;
  }
  </code></pre>
  
  <p>/* file.csv</p>
  
  <pre><code>301,36,15
  302,88,75
  </code></pre>
  
  <p><em>/
  /</em> my output</p>
  
  <pre><code>record[0]: a = 301 b = 36 c = 15
  record[1]: a = 302 b = 88 c = 75
  </code></pre>
  
  <p>*/</p>
  
  <p>I have 2 issues with above code..</p>
  
  <p>1st issue is :
  /* file.csv</p>
  
  <pre><code> 301,,15
   302,88,
   ,,,34
  </code></pre>
  
  <p>The output should be</p>
  
  <pre><code>record[0]: a = 301 b = 0 c = 15
  record[1]: a = 302 b = 88 c = 0
  record[2]: a = 0 b = 0 c = 34
  </code></pre>
  
  <p>and the 2nd issue is it should read file until “eof”. here I have taken 50 as a static line number value. what changes I should make ?</p>
  
  <p>see I have changed code at this way...</p>
  
  <pre><code>  const char* getfield(char* line, int num) {
          const char* tok;
          for (tok = strtok(line, ",");
                  tok &amp;&amp; *tok;
                  tok = strtok(NULL, ",\n"))
          {
              if (!--num)
                  return tok;
          }
          return NULL;
      }
  
      int main()
      {
          FILE* stream = fopen("b.csv", "r");
          char line[1024];
          char *pstr;int num;
           const char* value;
  
          while (fgets(line, 1024, stream))
          {
              char* tmp = strdup(line);
          //printf("Field 3 would be %s\n", getfield(tmp, 3));    
          value=getfield(tmp, 3);
          num =strtol(value,&amp;pstr,10);
          printf("Field 3 would be %d\n", num);
          // NOTE strtok clobbers tmp
              free(tmp);
          }
      }
  </code></pre>