c语言的结构体与结构体文件的调用问题

来源:百度知道 编辑:UC知道 时间:2024/09/18 03:53:38
#include <stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
struct shop{
char ID[6];
char sname[10];
float price;
}str,*ps=&str;
void main()
{
int i;
FILE *p,*p1;
if((p=fopen("price.dat","r"))==NULL)
{
printf("fafsda");
getch();
exit(0);
}
if((p1=fopen("jing.log","w"))==NULL)
{
printf("hagkfj");
getch();
exit(0);
}
fread(ps,sizeof(struct shop),1,p);
fwrite(ps,sizeof(struct shop),1,p1);
printf("%s",ps->ID);
price.dat的内容为11034 asping 13.3.
为什么我printf("%s",ps->ID)输出来的结果为11034 asping 13.3呢,而不是我想要的11034呢?,,急速求解!!!!!!!!!!!!!!!!!!!!
虽然我没多少分可以送了,但我真的会感激大家的

首先,你那个文件里面的数据都是字符型的。
如果你想读取文件里面的数据到对应的数据类型的话,请用fscanf()函数。

#include <stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
struct shop{
char ID[6];
char sname[10];
float price;
}str,*ps=&str;
int main()
{
int i;
FILE *p,*p1;
if((p=fopen("price.dat","r"))==NULL)
{
printf("fafsda");
getch();
exit(0);
}
if((p1=fopen("jing.log","w"))==NULL)
{
printf("hagkfj");
getch();
exit(0);
}
/*
* 这个函数将不能达到你所预期的效果
* fread(ps,sizeof(struct shop),1,p);
*/
fscanf(p, "%s%s%f", ps->ID, ps->sname, &(ps->price)); /* 用格式化输入,用法跟scanf一样,应该说scanf()用法跟fscanf()一样... */
fwrite(ps,sizeof(struct shop),1,p1);
printf("%s",ps->ID);
return 0;
}