I'm having some trouble finding a solution for splitting a file single line in c. There is a .txt file like this:
9999 m 32
9998 f 20
9997 o 22
9996 m 18
9995 o 45
9994 f 40
9993 m 76
where, for example, 9994 f 40
, 9994
is an int, f
a char and 40
another int.
I was trying to use fgets()
to take the line and separate it afterwards but i'm not finding a way to split the line information in three so i can use them the way it's needed.
There is another function other than fgets()
that is better for this? Or there is a way to do it with fgets()
?
You can read the text file line by line using fgets
and get int
and char
values from string using sscanf
:-
char line[30]; // read line by line input from file in this
int a,b;
char c;
while(fgets(line, 30, file) != NULL){ // file is your file pointer
if(sscanf(line, "%d %c %d", &a, &c, &b) == 3){
printf("%d %c %d\n", a,c,b);
}
}