fwrite,fread函数,懂的帮看看
#include<stdio.h>#include<io.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<conio.h>
#define LEN 100
typedef struct
{
char bookid[6];
char bookname[30];
int price;
int qty;
char flag[3];
}book;
int main()
{
FILE *fptr;
char fpath[LEN],t_price[10],t_qty[10];
int fno,fsize,rectot;
book mybook;
printf("请选择功能->1.打开新文件 2.打开旧文件: ");
if(getche()=='1')
{
printf("\n请输入文件路径:");
gets(fpath);
fptr=fopen(fpath,"w+");
}
else
{
printf("\n请输入旧文件路径: ");
gets(fpath);
fptr=fopen(fpath,"a+");
}
if(fptr==NULL)
{
printf("%s文件打开失败\n",fpath);
exit(0);
}
while(1)
{
printf("\n请问是否继续添加新数据(Y/N): ");
if(toupper(getche())=='Y')
{
printf("\n请输入要添加的数据: \n");
printf("书号: ");
gets(mybook.bookid);
printf("书名: ");
gets(mybook.bookname);
printf("单价: ");
gets(t_price);
mybook.price=atoi(t_price);
printf("库存: ");
gets(t_qty);
mybook.qty=atoi(t_qty);
fwrite(&mybook,sizeof(mybook),1,fptr);
}
else
{
fclose(fptr);
break;
}
}
fptr=fopen(fpath,"r");
fno=fileno(fptr);
fsize=filelength(fno);
rectot=filelength(fileno(fptr))/sizeof(mybook);
printf("\n数据更新完成……\n");
printf("%s目前文件大小 %d Bytes\n",fpath,fsize);
printf("%s数据内容如下:\n",fpath);
printf("\n记录总笔数: %d\n",rectot);
while(fread(&mybook,sizeof(mybook),1,fptr)!=NULL)
{
printf("%6s %30s %5d %5d\n",mybook.bookid,mybook.bookname,mybook.price,mybook.qty);
}
fclose(fptr);
printf("\n");
return 0;
}
输入书号 001 书名 历史 单价200 库存 100,之后虽然能正确运行,但是打开文件却是乱码,为什么?