从文件中读取的一个结构体长度的内容。文件中的这段内容只对应前三个成员,为什么第四个成员的值不是垃圾值 ?
C Primer Plus第五版 14章课后编程练习14_7。程序实现从文件中读出每个记录并且在显示它时允许用户选择删除或修改该记录的内容。
第一次运行时文件是不存在的,按提示向文件中增加了内容。
第二次运行时 为什么从文件读了一断内容到结构体变量后,library[count].del的值就变为0了?
程序代码:
/* pe14-7.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 10 /* maximum number of books */
#define CONTINUE 0
#define DONE 1
#define YES 1
#define NO 0
struct book { /* set up book template */
char title[MAXTITL];
char author[MAXAUTL];
float value;
int delete;
};
int getlet(const char * s);
int getbook(struct book * pb);
void update(struct book * item);
int main(void)
{
struct book library[MAXBKS]; /* array of structures */
int count = 0;
int deleted = 0;
int index, filecount, open;
FILE * pbooks;
int size = sizeof (struct book);
if ((pbooks = fopen("book.dat", "r")) != NULL)
{
while (count < MAXBKS && fread(&library[count], size,
1, pbooks) == 1)
{
if (count == 0)
puts("Current contents of book.dat:");
printf("%s by %s: $%.2f\n",library[count].title,
library[count].author, library[count].value);
printf("Do you wish to change or delete this entry?<y/n> ");
if (getlet("yn") == 'y')
{
printf("Enter c to change, d to delete entry: ");
if (getlet("cd") == 'd')
{
library[count].delete = YES;
deleted++;
puts("Entry marked for deletion.");
}
else
update(&library[count]);
}
count++;
}
fclose(pbooks);
}
filecount = count - deleted;
if (count == MAXBKS)
{
fputs("The book.dat file is full.", stderr);
exit(2);
}
puts("Please add new book titles.");
puts("Press [enter] at the start of a line to stop.");
open = 0;
while (filecount < MAXBKS)
{
if (filecount < count)
{
while (library[open].delete == NO)
open++;
if (getbook(&library[open]) == DONE)
break;
}
else if (getbook(&library[filecount]) == DONE)
break;
filecount++;
if (filecount < MAXBKS)
puts("Enter the next book title.");
}
puts("Here is the list of your books:");
for (index = 0; index < filecount; index++)
if (library[index].delete == NO)
printf("%s by %s: $%.2f\n",library[index].title,
library[index].author, library[index].value);
if ((pbooks = fopen("book.dat", "w")) == NULL)
{
fputs("Can't open book.dat file for output\n",stderr);
exit(1);
}
for (index = 0; index < filecount; index++)
if (library[index].delete == NO)
fwrite(&library[index], size, 1, pbooks);
fclose(pbooks);
puts("Done!");
return 0;
}



