当前位置:系统粉 > 电脑问答 > 其他问答 > 在C语言中,如何将结构体输入文件?急救啊!

在C语言中,如何将结构体输入文件?急救啊!

提问者:和谐锦城  |  浏览 次  |  提问时间:2017-01-23  |  回答数量:3

在C语言中,如何将结构体输入文件?急救啊!哪位可以告诉我在C语言中,如何将结构体输入文件?先谢谢啦!

已有3条答案
→小盆友君←

→小盆友君←

回答数:192  |  被采纳数:82

2017-01-23 23:49:17
#include<stdio.h>
#include<string.h>
struct Person
{
char name[100];
int age;
int sex;
char add[100];

};
int main(int argc, char* argv[])
{
FILE *FIN;
char STRING_COMMAND[30];
if((FIN=fopen("c:/abc.txt","a+"))==NULL)
{
printf("不能打开该文件,或者找不到该文件~");
return 0;
}
else
{
printf("请使用以下命令来完成操作:\n");
}

printf("-lsall list all the person`s info! \n");
printf("-insert insert one person`s info \n");
printf("-exit exit the progronam \n");
printf("-lsname list all the person`s name \n");
printf("-lsnameinfo[name] display the info of one person \n");
while(1)
{
gets(STRING_COMMAND);
if(strcmp(STRING_COMMAND,"-lsall")==0)
{ fseek(FIN,0,SEEK_SET);
char in;
in=getc(FIN);
while(in!=EOF)
{
printf("%c",in);
in=getc(FIN);
}
printf("Query successfully!\n");
continue;
}
else if(strcmp(STRING_COMMAND,"-insert")==0)
{
struct Person newPerson;
printf("name:");
scanf("%s",&newPerson.name);
printf("age:");
scanf("%d",&newPerson.age);
printf("sex:");
scanf("%d",&newPerson.sex);
printf("address:");
scanf("%s",&newPerson.add);
fseek(FIN,0,SEEK_END);
fprintf(FIN,"name:%s\nage:%d\nsex:%d\naddress:%s\n",newPerson.name,newPerson.age,newPerson.sex,newPerson.add);
printf("Insert successfully!\n");
continue;
}
else if(strcmp(STRING_COMMAND,"-lsname")==0)
{
fseek(FIN,0,SEEK_SET);
struct Person QueryName;
while(feof(FIN)==0)
{
fscanf(FIN,"name:%s\n",&QueryName.name);
fscanf(FIN,"age:%d\n",&QueryName.age);
fscanf(FIN,"sex:%d\n",&QueryName.sex);
fscanf(FIN,"add:%s\n",&QueryName.add);
printf("%s\n",QueryName.name);
}
printf("Query successfully!");
}
else if(strcmp(STRING_COMMAND,"-lsnameinfo")==0)
{ char ForCmp[20];
gets(ForCmp);
fseek(FIN,0,SEEK_SET);
struct Person QueryName;
while(feof(FIN)==0)
{
fscanf(FIN,"name:%s\n",&QueryName.name);
fscanf(FIN,"age:%d\n",&QueryName.age);
fscanf(FIN,"sex:%d\n",&QueryName.sex);
fscanf(FIN,"add:%s\n",&QueryName.add);
if(strcmp(QueryName.name,ForCmp)==0)
{
printf("name:%s\n",QueryName.name);
printf("age:%d\n",QueryName.age);
printf("sex:%d\n",QueryName.sex);
printf("address:%s\n",QueryName.add);
}
}
printf("Query successfully!");
}
else if(strcmp(STRING_COMMAND,"-exit")==0||strcmp(STRING_COMMAND,"-end")==0)
{
break;
}
else
{
printf("Bad command!\n");
}
}
fclose(FIN);
return 0;
}

自己参考下吧
赞 19
恋·夏依然

恋·夏依然

回答数:107  |  被采纳数:23

2017-01-23 23:14:43
将结构体指针强制转换成unsigned char*,然后直接写入文件
赞 10
饶花花

饶花花

回答数:72  |  被采纳数:17

2017-01-24 03:40:05
o,谢谢,我试试
赞 7
解决方法
版权信息

Copyright @ 2011 系统粉 版权声明 最新发布内容 网站导航