title: Parse lines of integers in C
body: <p>This is a classical problem, but I can not find a simple solution.</p>
  
  <p>I have an input file like:</p>
  
  <pre><code>1 3 9 13 23 25 34 36 38 40 52 54 59 
  2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114 
  2 4 9 15 23 27 34 36 63 67 76 85 86 90 93 99 108 115 
  1 25 34 36 38 41 52 54 59 63 67 76 85 86 90 93 98 107 113 
  2 3 9 16 24 28 
  2 3 10 14 23 26 34 36 39 41 52 55 59 63 67 76 
  </code></pre>
  
  <p>Lines of different number of integers separated by a space.</p>
  
  <p>I would like to parse them in an array, and separate each line with a marker, let say <code>-1</code>.</p>
  
  <p>The difficulty is that I must handle integers and line returns.</p>
  
  <p>Here my existing code, it loops upon the scanf loop (because scanf can not begin at a given position).</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  int main(int argc, char **argv) {
  
    if (argc != 4) {
      fprintf(stderr, "Usage: %s &lt;data file&gt; &lt;nb transactions&gt; &lt;nb items&gt;\n", argv[0]);
      return 1;
    }
    FILE * file;
    file = fopen (argv[1],"r");
    if (file==NULL) {
      fprintf(stderr, "Error: can not open %s\n", argv[1]);
      fclose(file);
      return 1;
    }
    int nb_trans = atoi(argv[2]);
    int nb_items = atoi(argv[3]);
    int *bdd = malloc(sizeof(int) * (nb_trans + nb_items));
    char line[1024];
    int i = 0;
  
    while ( fgets(line, 1024, file) ) {
      int item;
      while ( sscanf (line, "%d ", &amp;item )){
        printf("%s %d %d\n", line, i, item);
        bdd[i++] = item;
      }
      bdd[i++] = -1;
    }
  
    for ( i = 0; i &lt; nb_trans + nb_items; i++ ) {
      printf("%d ", bdd[i]);
    }
    printf("\n");
  }
  </code></pre>