我目前正在尝试编写一个程序来使用独立的头文件中的预构建结构来读取bin文件。我能够使程序使用该结构直接写出Bin文件中的内容,但是在将其定向到数组中时我迷路了。每当我尝试插入要首先读取的数组时,程序就会停止工作并崩溃。
这是我当前的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "project7.h"
int main() {
struct game_structure Game;
FILE * fp;
fp = fopen("games.bin", "rb");
while (1) {
fread(&Game, sizeof(Game), 1, fp);
if (feof(fp)) {
break;
}
printf("\nTitle: %s", Game.gameName);
printf("\nGenre/Game Type: %s", Game.gameType);
printf("\nDeveloper: %s", Game.developer);
printf("\nReview Score: %d", Game.reviewScore);
printf("\nGame Length: %.2lf", Game.gameLength);
printf("\nAmount Sold: %d", Game.amountSold);
printf("\n");
}
printf("\nFinished\n");
fclose(fp);
return 0;
}
这是自定义头文件中的内容:
#include <stdio.h>
#include <stdlib.h>
typedef struct game_structure
{
char gameName[20]; // Name of the game
char gameType[30]; // Video game or physical game? Activity or boardgame?
char developer[30]; // Who created the game?
int reviewScore; //What was the review score? Let's just use 1-5 for simplicity.
double gameLength; /* How many hours does it take to complete? Use
whole numbers for hours, followed by period and then the minutes. I.E.
6.30 means 6 hours and 30 minutes. */
int amountSold; //How many copies of the game have been sold?
} Game;
从本质上讲,即使首先将其写入数组比较麻烦,这也是我需要做的。如何将多个可能的结构输入写入数组?结构的每个部分都有5个不同的输入,因此我需要能够将它们全部存储到一个数组中,然后使用结构其他部分的正确输入来调用每个不同的输入。