简体   繁体   中英

How do I load data from a txt file into variables in my C program?

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

I won't be writing the code, but can try to help with the algotihm, in general.

  1. Open the file. Help : fopen()
  2. Check for successful opening. Hint: Return value.
  3. Read a line from the file. Check for the success. Help : fgets() and Return value.
  4. Based on data pattern , tokenize the read line and store into the array. Help : strtok()
  5. Continue until token is NULL.

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

  1. uncomment // exit(1); , you really should (note, not MUST, you can skip also) exit if the fopen() failed.

  2. 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 .

  3. fgets() reads and stores the trailing \\n . You may want to get rid of that.

  4. Use counter to track the structure array member index, too. Your array has only 8 elements here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM