学生程序员在这里。我在从 C 中的二进制文件读取输入时遇到问题。文件中存储的数据是如下所示的结构:
typedef struct reserve{
char *name;
char *ic;
int room_number;
} Reserve;
将结构写入二进制文件时没有问题。这是我为写入文件所做的代码:
void reg_new() //Make a new reservation
{
Reserve newReserve = {"", "", 0};
char name[NAMEFIELD], ic[ICFIELD];
int room_number;
FILE *resvptr;
scanf_s("%s", name, NAMEFIELD);
scanf_s("%s", ic, ICFIELD);
scanf_s("%d", &room_number);
newReserve.name = name;
newReserve.ic = ic;
newReserve.room_number=room_number;
resvptr = fopen("reservations.dat", "wb");
fwrite(&newReserve, sizeof(Reserve), 1, resvptr);
fclose(resvptr);
}
以及从文件中读取的代码:
void reg_view() //view a reservation.
{
FILE *seekptr;
Reserve viewReserve = {"", "", 0};
int read;
if ( (seekptr = fopen("reservations.dat", "rb")) == NULL)
{
puts("Error: file could not be found.");
}
else
{
while ( !feof(seekptr))
{
read = fread(&viewReserve, sizeof(Reserve), 1, seekptr);
if(read != 0)
{
printf("Name: %s\nIC number: %s\nRoom Number: %d\n", viewReserve.name, viewReserve.ic, viewReserve.room_number);
}
}
fclose(seekptr);
}
在写入二进制文件并访问读取函数后,房间号(int 值)读取正常,但两个字符串(名称和 IC 号)读取为垃圾字符。随后,关闭并重新启动程序,然后尝试从文件中读取将给我一个访问冲突和错误的指针错误。
问题在于从文件中读取字符串。我怀疑内存泄漏,但我不能肯定地说......有人可以帮忙吗?谢谢。