非高手勿进!(一个关于C 文件的送分题!)

来源:百度知道 编辑:UC知道 时间:2024/06/02 16:24:23
下面是我的一个关于文件操作的代码:
#include<stdio.h>
#include<string.h>
struct infor
{
char name[20];
int num;
char state[15];
int amount;
char author[20];
char addr[10];
char company[20];
struct infor *next;

}data[2],*head,*p;
main()
{
FILE *fp;
int i;

if((fp=fopen("data","wb"))==NULL)
{
printf("Cannot open file strike any key exit!");
getch();
exit(0);
}
printf("\ninput data\n");p=head=&data[0];
for(i=0;i<2;i++)
{
printf("please input the name of the book: ");
gets(data[i].name);
printf("please input the Publishing Company of the book: ");
gets(data[i].company);
printf("please input the author of the book: ");
gets(data[i].author);
printf("please input Storage address: ");
gets(data[i].addr);

你对缓冲区接受不可预知的转义字符的处理是用一个getchar()来进行的,但是往往用getchar()接受回车转义字符无法预见,所以最保险的方法还是刷新缓冲区,fflush(stdin);
还有fwrite要配合fread使用。这里用fprintf就行了

修改程序如下:

#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
struct infor
{
char name[20];
int num;
char state[15];
int amount;
char author[20];
char addr[10];
char company[20];
struct infor *next;

}data[2],*head,*p;
void main()
{
FILE *fp;
int i;

if((fp=fopen("data.txt","wb"))==NULL)
{
printf("Cannot open file strike any key exit!");
getch();
exit(0);
}
printf("\ninput data\n");
p=head=&data[0];
for(i=0;i<2;i++)
{
printf("please input the name of the book: ");
gets(data[i].name);
printf("please inpu