我有一些麻煩閱讀數據從一個文件中的數組內存分配的結構在c。我的相關代碼如下:從文件掃描到Mallocated Structs數組中? (c)
//Struct that holds the restaurant information
typedef struct
{
char *name;
char *food;
double *price;
int *rating;
}RESTAURANT;
//Function to get all the reviews from the file
void reviews()
{
int numReviews, i;
char tempBuffer[BUFFER_SIZE]; //hold the user input
RESTAURANT *reviews; //create an array of structs
FILE *inputFile; //file pointer
inputFile = fopen(INPUT_FILE_NAME, "r"); //open the input file
//Get the number of reviews from the top of the file
fgets(tempBuffer, BUFFER_SIZE, inputFile);
sscanf(tempBuffer, "%d", &numReviews);
//Allocate enough space in the struct array for the number of reviews
reviews = malloc(sizeof(*reviews)*numReviews);
//Loop to allocate memory for each field in each struct
for(i = 0; i < numReviews; i++)
{
reviews[i].name = malloc(sizeof(char *));
reviews[i].food = malloc(sizeof(char *));
reviews[i].price = malloc(sizeof(double *));
reviews[i].rating = malloc(sizeof(int *));
}
//Loop to get each field for each struct from the file
//And store it in the struct array at the correct struct
for(i = 0; i < numReviews; i++)
{
fscanf(inputFile, "%s", reviews[i].name);
fscanf(inputFile, "%s", reviews[i].food);
fscanf(inputFile, "%lf", reviews[i].price);
fscanf(inputFile, "%d", reviews[i].rating);
}
而在reviews.txt該文件是:
4
Chili's
AmericanizedMexican
10.95
3
BurgerKing
American
4.50
2
IHOP
American
9.50
1
OliveGarden
AmericanizedItalian
11.00
4
在讀池莉和AmericanizedMexican工作正常。但是,當我嘗試打印辣椒的價格或評級時,價格總是打印0.0
,評級總是超過100萬。我在這裏做錯了什麼?我猜它必須是一些與內存或用的東西,我的意思的方式來讀取它分配。
兩件事情:第一,你寫在寫實際的字符串之前字符串的大小?因爲字符串大小可變,所以它看起來像。其次,你可能想使用fread,fwrite,fopen和fclose。閱讀手冊頁。 – Gophyr 2014-11-14 14:22:43
@Gophyr:OP在未顯示的代碼中使用'fopen',也可能使用'fclose'。 「fread」如何在這裏幫助?數據是ASCII數據,可以用'fgets'和'fscanf'讀取。 'fread'用於已知字節大小的數據。在代碼中,什麼也沒有寫;它是關於從文件中讀取的。 – 2014-11-14 14:26:27
'fread'和'fwrite'允許您控制讀取/寫入元素的大小和數量。 – Gophyr 2014-11-14 15:36:44