简体   繁体   中英

Reading a file into a struct C

I am working on an assignment that puts takes a file containing a recipe and creates an instance of a struct to store the information. This is the format that my struct follows:

struct Dinner
{
       char* recipeName;
       unsigned numMainDishIngredients;
       char** mainDishIngredients;
       unsigned numDessertIngredients;
       char** DessertIngredients;
};

I need to figure out how to use a read in a file which will be structured as follows: The first line will contain the name of the recipe, the second line will be the number of ingredients in the main dish, then the next lines will each contain one ingredient that is in the main dish until one blank line is hit. The line following the blank line will contain the number of ingredients in the dessert and the following lines will each contain a dessert ingredient.

An example is as follows:

Pizza and Ice Cream
4
Dough
Cheese
Sauce
Toppings

3
Cream
Sugar
Vanilla

I am mostly unsure of how to read into the char** types. So far this is all I have:

struct Dinner* readRecipe(const char* recipeFile)
if (!recipeFile)
{
       return NULL;
}
File* file = fopen(recipeFile, "r");
if (!file)
{
      return NULL;
}
char recipeName[50];    // specified that strings wont exceed 49 chars
int numMainIngredients, numDessertIngredients;
fscanf(file, "%s, %d", &recipeName, numMainIngredients);

...

}

Basically I do not know how to read multiple lines of a file into an array type in a structure and I would really appreciate any tips on how to do this.

Reading from a file is pretty straight forward. Most of the std functions are designed to read a single line from the file, then move to the next line automatically. So all you really need to do, is loop.

I recommend that you write the following

#define MAXCHAR 256
char[MAXCHAR] line;
while(fgets(line, MAXCHAR, file) != NULL)
{
  // line now has the next line in the file
  // do something with it. store it away
  // use atoi() for get the number?
  // whatever you need.
}

That is, we use fgets() to grab the next line in the file; and if we loop that a bunch; it will read until the end of file (EOF).

Note that I used fgets() instead of fscanf() . fgets() is a safer and more efficient option than fscanf. Granted, it does not come with the fancy ability to specify line formatting and such; but it's not too difficult to do that on your own.

edit: I mixed up my languages pretty badly.. fixed it.

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