c - 将文件读入结构 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 更安全、更高效的选择。当然,它没有指定行格式等的花哨的能力;但是自己做这件事并不太难。
编辑:我把我的语言混得很糟糕..修复了它。
推荐阅读
- javascript - 当有“touch-action: pan-x !important;”时,HammerJS 滑动不起作用
- javascript - Webpack JS-loader 解析模块依赖
- java - Bits representation of number String vs Integer in Java
- node.js - 无法在nodejs中导入没有.js扩展名的模块
- c# - ML.Net 以及如何使 K-Means 具有确定性?
- django - 在 GitHub 公共存储库上发布实时站点代码的安全问题
- reactjs - react-day-picker 中的每周 callendar 视图
- java - java - 如何在Java的for循环中强制转换为子类?
- jquery - 如何将我的 selectInput 链接到我的 DataTable 以根据选择更新表?(这是R闪亮)
- snowflake-cloud-data-platform - 从雪花 java UDF 读取外部阶段文件