Reputation: 295
I am reading a file in C that is formatted like this
int int int int char double double
but repeated a known number of times. (The first line of the file, not listed in the sample, specifies the number of times this sequence will repeat) I want to parse these values into a structure. However, I am not sure how to read these elements as they have different datatypes, I was looking at three different methods
fread --> does not work because the different elements are of different data types and wont have the same number of bytes.
fscanf --> does not work because of multiple different data types
fgets--> does not work becase it only stops once there is a newline character.
So I am not sure what to do about this. Maybe I am looking to hard for an elegant solution to loading a file with ugly input like this, or maybe I am overlooking something in one of the functions that I have already mentioned.
This is for a school project btw, but I am not asking for an answer, just a hint.
I am limited to what I can use in the stdio and the stdlib libraries.
thanks for all the help
Upvotes: 0
Views: 4967
Reputation: 206627
To elaborate on the earlier answers, you would need something like:
int intVar1;
int intVar2;
int intVar3;
int intVar4;
char c;
double doubleVar1;
double doubleVar2;
fscanf(file, "%d %d %d %d %c %lf %lf",
&intVar1,
&intVar2,
&intVar3,
&intVar4,
&c,
&doubleVar1,
&doubleVar2);
Upvotes: 1
Reputation: 3162
you can use any of those functions to read from the file. the easiest to use for this case is fscanf()
you can read inside a loop since you know the number of times to read by just iterating known number of times.
fscanf(fd,"%d %d %d %d %d %c %lf %lf",&a,&b,&c,&d,&e,%f,&h)
or you can create a structure
struct data
{
int a;
int b;
int c;
int d;
char e;
double h;
double i;
}var1;
and use it in fscanf() to fill the value for its members
Upvotes: 1
Reputation: 23268
fscanf
should work.
fscanf(file, "%d %d %d %d %c %lf %lf", ....);
Upvotes: 1