user3402584
user3402584

Reputation: 410

Reading from txt file in C using scanf

i have a txt file and i want to read from it. I know that i will have to read 20 lines(each line contain 3 number variables,for instance 10 5 6 and so on)

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
int x,y,z;
int counter = 0;

FILE *fid;   
fid = fopen(argv[1],"r");

while(counter<20){
    sscanf(fid,"%d%d%d",&x,&y&z);
    //some operations made on x,y,z
    counter=counter+1;
}

fclose(fid) ;
return 0;
}

Unfortunately it is not working. I want to go through file and use sscanf(fid,"%d%d%d",&x,&y,&z) 20 times. Maybe i should scanf?I would be grateful if somebody could tell me how to make this working.

Upvotes: 0

Views: 12332

Answers (2)

whalesf
whalesf

Reputation: 49

sscanf should change to fscanf

fscanf scan file.

sscanf scan string.

  1. fscanf function

The fscanf function reads data from the current position of the specified stream into the locations given by the entries in the argument list, if any. The argument list, if it exists, follows the format string.

int fscanf (FILE *:stream, const char *format, …);

2.sscanf function

The sscanf function reads data from buffer into the locations given by argument list. Reaching the end of the string pointed to by buffer is equivalent to the fscanf function reaching the end-of-file (EOF). If the strings pointed to by buffer and format overlap, the behavior is not defined.

int sscanf(const char *buffer, const char *format, …);

Quote from this website

Upvotes: 0

Vagish
Vagish

Reputation: 2547

sscanf takes first argument of type const char *.You are passing the first argument as FILE *.

You can use:

  1. fscanf

OR

  1. fgets with sscanf

Upvotes: 2

Related Questions