title: Reading an arbitrary number of space-separated chars from a line in file
body: <p>I have a file, which, at one line has an arbitrary number of numbers to be read as integers. In a minimal, reproducible example, I created a file <code>test.dat</code> that contains the following line only:</p>
  
  <pre><code> 1 2 3 4
  </code></pre>
  
  <p>I then try to use <code>fgets</code> and <code>strtok</code> to achieve this:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(){
  
  FILE* fileptr;
  
  fileptr = fopen("test.dat","r");
  char line[500];
  char *token;
  
  int array[20];
  int i = 0;
  
  fgets(line,300,fileptr);
  
  token = strtok(line," ");
  array[i] = atoi(token);
  printf("%d\n", array[i]);
  i++;
  
  while(token != NULL){
      token = strtok(line," ");
      array[i] = atoi(token);
      printf("%d\n", array[i]);
      i++;
  }
  
  return 0;
  }
  </code></pre>
  
  <p>But this results in printing 21 lines of <code>1</code>'s, followed by 632 lines of <code>0</code>'s. Finally it gives a segmentation fault because the <code>i</code> grows larger than 20, the allocated space for <code>array</code>. What I don't understand is why 600+ lines are printed, and why I can never read beyond the number <code>1</code> in the file. What am I missing?</p>
  
  <p>Note: I prefer to keep reading from the file with <code>fgets</code> because this is going to be a simple modification to an existing subroutine that reads an entire file.</p>