Reputation: 113
I have a program that has a struct of channels:
struct channel
{
char title[40];
float gain;
float offset;
};
int main (int argc, char **argv)
{
struct channel channels[8];
}
And a text file called configurationSettings.txt
that holds the information needed to fill up 8 channels:
Title1
20
30
Title2
10
0
Title3
34
03
...
How would I go about pulling the data from the text file and into their appropriate variables?
EDIT:
Here is the direction I'm heading so far:
FILE *fptr;
if ((fptr=fopen("configurationSettings.txt","r"))==NULL){
printf("\n\nConfiguration file not found.\n");
// exit(1); // Program exits if file pointer returns NULL.
}
while (1) {
if (fgets(loadedTitle,150, fptr) == NULL) break;
if (fgets(loadedGain,150, fptr) == NULL) break;
if (fgets(loadedOffset,150, fptr) == NULL) break;
printf("%s", loadedTitle);
printf("%s", loadedGain);
printf("%s", loadedOffset);
strcpy(channels[i].title, loadedTitle);
loadedGain == channels[i].gain;
loadedOffset == channels[i].offset;
}
printf("\n\n%s", channels[i].title);
printf("%f", channels[i].gain);
printf("\n%f", channels[i].offset);
fclose(fptr);
Here is the output I get. It's basically just printing everything and storing the last line as the first variable. This is definitely not what I want.
Title 1
10
30
Title 2
50
0
Title 3
38
20
20
Upvotes: 1
Views: 3149
Reputation: 134326
I won't be writing the code, but can try to help with the algotihm, in general.
fopen()
fgets()
and Return value.strtok()
Note: At point 4, you need to convert some of the tokens to float
type. Help: strtod()
EDIT:
Appriciate adding the code. Feedback for your code
uncomment // exit(1);
, you really should (note, not MUST, you can skip also) exit if the fopen()
failed.
fgets()
reads one line at at time. So basically, you need three consecutive fgets()
to populate one instance of the structure. first fgets()
will give title
, second one gain
, third one offset
.
fgets()
reads and stores the trailing \n
. You may want to get rid of that.
Use counter to track the structure array member index, too. Your array has only 8 elements here.
Upvotes: 5