Read int values from a text file in C

elh mehdi picture elh mehdi · Jan 5, 2011 · Viewed 190.5k times · Source

I have a text file that contains the following three lines:

12 5 6
4 2
7 9

I can use the fscanf function to read the first 3 values and store them in 3 variables. But I can't read the rest. I tried using the fseek function, but it works only on binary files.

Please help me store all the values in integer variables.

Answer

Vijay Mathew picture Vijay Mathew · Jan 5, 2011

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}