使用fread读取文件以后,显示结果不正确
使用fread读取文件之后,显示结果不正确
程序文件执行结果:
/**
*把结构数组中的内容保存到指定的文件中
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTITL 40
#define MAXAUTH 40
#define MAXBOKS 100
struct book {
char title[MAXTITL];
char author[MAXAUTH];
float value;
};
int main(void)
{
FILE *fp;
int count=0, filecount;
int index;
int size = sizeof(struct book);
struct book library[MAXBOKS];
if((fp=fopen("book.dat", "a+b")) == NULL){
printf("Error in openning book.dat.\n");
exit(1);
}
rewind(fp);
/*使用fread读取book.dat中的信息,使用printf显示所读取的信息。*/
/*printf显示信息不正确,缺少书名和作者信息*/
while(fread(&library[count], size, 1, fp) == 1 && count<MAXBOKS){
if(count == 0)
printf("Current book list of the book.dat: \n");
printf("%s by %s: $%.2f.\n", library[count].title,
library[count].author, library[count++].value);
//问题在此,printf不能正确显示书名和作者信息
}
filecount = count;
if(count == MAXBOKS){
printf("Upper to the limmit of the book.dat.\n");
exit(2);
}
printf("Now, add the new list.\nPlease enter the title: ");
while(fgets(library[count].title, MAXTITL-1, stdin) != NULL &&
library[count].title[0] != '\n' && count<MAXBOKS){
library[count].title[strlen(library[count].title)-1] = '\0';
printf("Please enter the author: ");
fgets(library[count].author, MAXAUTH-1, stdin);
library[count].author[strlen(library[count].author)-1] = '\0';
printf("Please enter the value: ");
scanf("%f", &library[count++].value);
if(getchar() == '\n')
;
if(count < MAXBOKS)
printf("Please enter the next title: ");
}
if(count > 0){
printf("Now, there is your library:\n");
for(index=0; index<count; index++)
printf("%s by %s: $%.2f.\n", library[index].title,
library[index].author, library[index].value);
fwrite(&library[filecount], size, count-filecount, fp);
}
else
printf("No list? So bad...\n");
printf("Bye Bye!\n");
return 0;
}
程序文件执行结果: