首页 > 解决方案 > 将文件读入结构 C

问题描述

我正在做一个作业,它接受一个包含配方的文件并创建一个结构的实例来存储信息。这是我的结构遵循的格式:

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

我需要弄清楚如何在一个结构如下的文件中使用读取:第一行将包含食谱的名称,第二行将是主菜中的成分数量,然后下一行将每个都包含一种主菜中的成分,直到一个空白行被击中。空白行之后的行将包含甜点中成分的数量,以下各行将包含甜点成分。

一个例子如下:

Pizza and Ice Cream
4
Dough
Cheese
Sauce
Toppings

3
Cream
Sugar
Vanilla

我主要不确定如何读入 char** 类型。到目前为止,这就是我所拥有的:

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

...

}

基本上我不知道如何将文件的多行读入结构中的数组类型,我非常感谢有关如何执行此操作的任何提示。

标签: cfilestructscanfreadfile

解决方案


从文件中读取非常简单。大多数 std 函数旨在从文件中读取一行,然后自动移动到下一行。所以你真正需要做的就是循环。

我建议您编写以下内容

#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.
}

也就是我们fgets()用来抓取文件的下一行;如果我们循环那一堆;它将一直读取到文件结尾 (EOF)。

请注意,我使用fgets()而不是fscanf(). fgets()是比 fscanf 更安全、更高效的选择。当然,它没有指定行格式等的花哨的能力;但是自己做这件事并不太难。

编辑:我把我的语言混得很糟糕..修复了它。


推荐阅读