Search code examples
cpointersfile-handlingturbo-c

How do I assign an integer in a line in a text file to a variable in c?


I have a text file in which numbers were fed by fprintf("%d\n",var); Now the structure of file is: number 1 number 2 number 3 number 4 etc i want to assign number 1 to var_x,number 2 to var_y,number 3 to var_z then print all variables then assign number 4 to var 1 and so on How do i do it?

I tried sscanf fscanf etc. but it just prints random numbers

this is how i am filling numbers in the file:

      fprintf(save_file,"%d\n",xaxis);
      fprintf(save_file,"%d\n",yaxis);
      fprintf(save_file,"%d\n",getpixel(xaxis,yaxis));

this how the result file looks like:

30
20
0
31
21
15
32
22
0 etc

this is what i am trying right now:

sscanf(open_file,"%d",&read_x);
sscanf(open_file,"%d",&read_y);
sscanf(open_file,"%d",&read_colour);
while(!feof(open_file))
{
   printf("%d %d %d",read_x,read_y,read_colour);
   sscanf(open_file,"%d",read_x);
   sscanf(open_file,"%d",read_y);
   sscanf(open_file,"%d",read_colour);

}

expected result is:

30 20 0
31 21 15
32 22 0


Solution

  • You can fscanf all 3 values at once:

    #include <stdio.h>
    
    int main() {
        FILE* f = fopen("input", "r");
    
        int x, y, z;
    
        while (fscanf(f, "%d %d %d", &x, &y, &z) > 0)
            printf("%d %d %d\n", x, y, z);
    }