[英]Reading a file into a struct 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);
...
}
基本上我不知道如何将文件的多行读入结构中的数组类型,我非常感谢有关如何执行此操作的任何提示。
从文件中读取非常简单。 大多数 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 更安全、更有效的选项。 当然,它没有指定行格式等的奇特功能; 但自己做这件事并不难。
编辑:我混淆了我的语言非常严重..修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.