35

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.

techenthu
  • 158
  • 11
elh mehdi
  • 359
  • 1
  • 3
  • 3

2 Answers2

60

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);        
}
Vijay Mathew
  • 26,737
  • 4
  • 62
  • 93
  • 3
    With this method you don't print the last value. Delete the first `fscanf` and put the `printf` below the `fscanf` – KKKKK Jul 22 '20 at 08:52
9

How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2); 

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

Md. Al Amin Bhuiyan
  • 303
  • 1
  • 3
  • 12
MAK
  • 26,140
  • 11
  • 55
  • 86