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

请问上,这个程序为何不能将数据写入文件

2013-02-06 
请教下,这个程序为何不能将数据写入文件#includestdio.h#includestdlib.h#define MAXTITL 40#define M

请教下,这个程序为何不能将数据写入文件

#include<stdio.h>
#include<stdlib.h>
#define MAXTITL 40
#define MAXAUTL 40
#define MAXBKS 5         //图书的本数
struct book{
char title[MAXTITL];
char author[MAXAUTL];
float value;
};
int main(void)
{
struct book library[MAXBKS];
int count=0,i,filecount;
FILE *fpb;
int size=sizeof(struct book);

if((fpb=fopen("book.txt","ab+"))==NULL)
{
puts("can't open file");
exit (1);
}
rewind(fpb);         //定位到文件开始
while(count<MAXBKS&&fread(&library[count],size,1,fpb)==1)
{
if(count==0)
puts("current contents of the book");
printf("%s by %s:$%.2f\n",library[count].title,library[count].author,library[count].value);
count++;
}
filecount=count;
if(count==MAXBKS)
exit(1);
while(count<MAXBKS&&gets(library[count].title)!=NULL&&library[count].title[0]!='\0')
{
puts("enter the author");
gets(library[count].author);
puts("enter the value");
scanf("%f",&library[count++].value);
while(getchar()!='\n')      //清空输入行
continue;
if(count<MAXBKS)
puts("enter the next title");
}
if(count>0)
{
puts("here is the book list");
for(i=0;i<count;i++)
printf("%s by %s:$%.2f\n",library[i].title,library[i].author,library[i].value);
fwrite(&library[filecount],count-filecount,1,fpb);
}
else
puts("no books");
puts("bye");
fclose(fpb);
}

该程序的作用是把书名保存到一个名为book.txt的文件中,如果文件存在,程序显示文件内容,然后允许添加内容。
当程序运行后文件中只有几个字母。每次再运行程序时都要重新添加。
[解决办法]
引用:
引用:
C/C++ code?123456#define MAXTITL 40#define MAXAUTL 40 int size=sizeof(struct book);  fread(&amp;amp;library[count],size,1,fpb)

问题就是出在这三条语句上了,你必须保证book.txt中的每个条目均占82字节,程序执……

没关系啦。

条目就是记录嘛,我平时不喜欢用记录这个词,一般用条目,item。。。

首先我调试了一下你的程序发现根本无法运行,然后我输出调试了下,发现问题就是那三句话。

类book必须要占据82字节吧,sizeof(book)会返回82吧。

int fread( void *buffer, size_t size, size_t num, FILE *stream );
函数fread()读取[num]个对象(每个对象大小为size(大小)指定的字节数),并把它们替换到由buffer(缓冲区)指定的数组. 数据来自给出的输入流. 函数的返回值是读取的内容数量

然后如果我在文本中写入的不是82字节的条目,读取就会出错,就是这样子喽。

热点排行