[英]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.