文本的存储....不懂,请教下

huanhuan30 2009-03-05 08:33:44
打开一个已经存储有 10个 struct book 结构的二进制文件。。。然后可以进行删除和修改..我写了如下程序,就是无法修改,不知道为什么!!
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN 10
#define MAXBKS 20

void Delete (struct book *);
void Alter (struct book *);
void EatLine (void);
struct book
{
char title[MAXBKS];
char author[MAXBKS];
float value;
};
int main (void)
{
struct book library[10];
FILE *pf;
int index;
int count = 0; // read calc
int choose; // n11
size_t size = sizeof(struct book);
if ((pf =fopen("xb.txt", "a+b")) == NULL)
{
puts("Can't open xb.txt");
exit(EXIT_FAILURE);
}
// rewind(pf);
while (count < LEN && fread(&library[count], size, 1, pf) == 1)
{
printf("%d. %s by %s $%.2f....\n", count+1, library[count].title, library[count].author, library[count].value);
count++;
}
puts("select a item to alter......");
puts("1. delete 2.alter");
while (scanf("%d", &choose) == 1)
{
switch (choose)
{
case 1: Delete(library); break;
case 2: Alter(library); break;
default : puts("not 1 or 2 ....");
}
puts("Enter others choose....");
}
rewind(pf);
for (index = 0; index < count; index++)
{
fwrite(&library, size, 1, pf);
}
return 0;
}
void Alter (struct book *pC)
{
int i;
puts("Enter the number you want to alter");
scanf("%d", &i);
EatLine();
puts("Enter the new title");
gets(pC[i-1].title);
puts("Enter the new author");
gets(pC[i-1].author);
puts("Enter the value...");
scanf("%f", &pC[i-1].value);
EatLine();
}
void Delete (struct book *pC)
{
int i;
puts("Enter the number your want to delete..");
scanf("%d", &i);
strcpy(pC[i-1].title, " ");
strcpy(pC[i-1].author, " ");
EatLine();
}
void EatLine (void)
{
while (getchar() != '\n')
{
continue;
}
}
...全文
65 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
就append模式就可以了,append也可以修改文件的.
yutaooo 2009-03-05
  • 打赏
  • 举报
回复

要么你打开2次文件,1次"a+b" 另1次"rb+"。

用2个fd支持不同的操作。fd1支持追加记录。fd2支持读和修改写回。
yutaooo 2009-03-05
  • 打赏
  • 举报
回复

a 是 append 呀。追加。

huanhuan30 2009-03-05
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 yutaooo 的回复:]
C/C++ codepf=fopen("xb.txt","a+b")

不是"a+b"吧。应该是 "wb+"。
[/Quote]
我是说已经有一个 含有 10 个struct book 的二进制文本文件....wb+的话就 清空了。。。。
yutaooo 2009-03-05
  • 打赏
  • 举报
回复

pf =fopen("xb.txt", "a+b")


不是"a+b"吧。应该是 "wb+"。

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧