在main方法里面,前半段注释了的是写入文件的代码,后半段是将写入的代码读出。
要注意两点:
第一,文件路径要写对,斜线用转义字符\\,否则会报出Debug inssertion failed
第二,在你将结构体写入的时候,查看文件可以会使乱码,因为他是以byte的形式写入的,别奇怪,只要能正确读出来就可以了。 当然如果你想要正确显示字符,还是改变一下解码方式吧。
/*Global inclusions*/
#include <stdio.h>
#include <stdafx.h>
#include <string.h>
#include <conio.h>
typedef struct ty_item
{
char iname[15];
int u_price;
int quan;
};
/*Main function*/
void main()
{
///*Define item structure*/
//ty_item t;
///*Define a file pointer*/
//FILE *fl;
//
//printf("Enter the intem details:\n");
///*Input data*/
//scanf("%s%d%d", t.iname, &t.u_price, &t.quan);
//
///*Open file*/
//fl = fopen("C:\\Documents\\Demo3.txt", "wb");
//fwrite(&t, sizeof(t), 1, fl);
//fclose(fl);
FILE *fl;
char ch;
ty_item t;
fl = fopen("C:\\Users\\I075181\\Documents\\Demo3.txt", "rb");
fread(&t, sizeof(t), 1, fl);
printf("\n");
printf("%s\t\%d\t%d\n", t.iname, t.u_price, t.quan);
fclose(fl);
getch();
}