我有一个数组被写入文件,但是当我调用函数时,我需要一种方法从文件中打印相同的信息。代码的第一部分在 main 函数中,第二部分是第二个函数,它打印出应该来自文件 ( fp
) 的值。
fp = fopen("Grue.txt", "wb");
for(i = 0; i < 5; i++)
{
char newLine[3] = {"\n"};
char space[2] = {" "};
fwrite(array[i].name, strlen(array[i].name), sizeof(char), fp);
fwrite(space, strlen(space), sizeof(char), fp);
fwrite(array[i].height, strlen(array[i].height), sizeof(char), fp);
fwrite(space, strlen(space), sizeof(char), fp);
fwrite(array[i].weight, strlen(array[i].weight), sizeof(char), fp);
fwrite(space, strlen(space), sizeof(char), fp);
fwrite(array[i].items, strlen(array[i].items), sizeof(char), fp);
fwrite(newLine, strlen(newLine), sizeof(char), fp);
}
fclose(fp);
fp = fopen("Grue.txt", "rb");
PrintAGrue(fp);
void PrintAGrue(FILE *a)
{
// create End of file character onto the array being saved,
int i;
char n;
char h;
char w;
char m;
for (i=0; i<5; i++)
{
n = fread(a[i].name, strlen(array[i].name, sizeof(char), a);
h = fread(array[i].height, strlen(array[i].height, sizeof(char), a);
w = fread(array[i].weight, strlen(array[i].weight, sizeof(char), a);
m = fread(array[i].items, strlen(array[i].items, sizeof(char), a);
printf("This grue is called %s and is %s feet tall, and weighs %s pounds, and has eaten %s things.", n, h, w, m);
}
}