首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

二次运作文件不正常。

2012-07-28 
二次运行文件不正常。。。第一次运行建立文件,追加了几个记录,第二次运行文件的时候,回显不正常,第一个记录没

二次运行文件不正常。。。
第一次运行建立文件,追加了几个记录,
第二次运行文件的时候,回显不正常,第一个记录没有书名和作者,
而且后面每个.value的值都是第一个.value的值,错误出在哪里了呢?

C/C++ code
//booksave.c   把结构内容保存到文件中  #include <stdio.h>#include <stdlib.h>       //为malloc()函数提供原型#define BOOKS 10    //最多容纳多少本书#define NAMES 40    //书名#define ZUOZHE 40   //作者名struct book{    char title[NAMES];    char author[ZUOZHE];    float value;};int main(int argc,char *argv[]){    struct book library[BOOKS];    FILE *fp;    int count = 0;    int filecount,index;    int size = sizeof(struct book);    if(argc != 2)    {        fputs("command error\n",stderr);        exit(1);    }    if((fp = fopen(argv[1],"a+b")) == NULL)    {        fprintf(stderr,"Can't open %s\n",argv[1]);        exit(2);    }    rewind(fp);    while(count < BOOKS && fread(&library[count],size,1,fp) == 1)    {        if(count = 0)            fprintf(stdout,"Current contents of %s:\n",argv[1]);        fprintf(stdout,"%s by %s: $%.2f\n",library[count].title,library[count].author,library[count++].value);    }    filecount = count;    if(count == BOOKS)    {        fprintf(stderr,"The %s file is full",argv[1]);        exit(3);    }    fputs("Please add new book titles.\n",stdout);    puts("Press [enter] at the start of a line to stop.");    while(count < BOOKS && gets(library[count].title) != NULL && library[count].title[0] != '\0')    {        puts("Now enter the author.");        gets(library[count].author);        puts("Now enter the value.");        scanf("%f",&library[count++].value);        while(getchar() != '\n')            continue;        if(count < BOOKS)            puts("Enter the next title");    }        if(count > 0)    {        puts("Here is the list of your books: ");        for(index = 0;index < count; index++)            fprintf(stdout,"%s by %s: $%.2f\n",library[index].title,library[index].author,library[index].value);        fwrite(&library[filecount],size,count - filecount,fp);    }    else        fputs("No books? Too bad.\n",stderr);    puts("Bye.\n");    fclose(fp);    return 0;}


[解决办法]
推荐使用WinHex软件查看文件或内存中的原始字节内容。

不要把
fopen("...","...");fscanf,fprintf,fclose //读时把\r\n替换成\n,写时把\n替换成\r\n;读到\x1a就设置EOF;读写的内容当字符看待

fopen("...","...b");fread,fwrite,fclose //不作以上替换,遇到\x1a仍继续读;读写的内容当字节看待
弄混了

热点排行