Search code examples
cfgetsfreadscanf

Reading a file in C with input with different data types


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


Solution

  • 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);