如何用C语言将结构体写入读出TXT文件,int型可以正常打印,可是char类型
发布网友
发布时间:2022-05-14 10:42
我来回答
共2个回答
热心网友
时间:2023-10-14 11:17
#include<stdio.h>
#define N 5
struct SS { int number; char name[20]; int age; };
void main()
{ struct SS stu[N]={ {1,"赵明",17},{2,"李广",16},{3,"钱兵",17},{5,"吴俊杰",18},{4,"孙菲",15} };
struct SS stu1[N];
int i; FILE *fp; char fnm[]={ "student.txt" };
if ( fp=fopen(fnm,"w+") )
{ for ( i=0;i<N;i++ ) fprintf(fp,"%d %s %d\n",stu[i].number,stu[i].name,stu[i].age);
fclose(fp);
if ( fp=fopen(fnm,"r") )
{ for ( i=0;i<N;i++ ) fscanf(fp,"%d %s %d",&stu1[i].number,&stu1[i].name,&stu1[i].age);
fclose(fp);
for ( i=0;i<N;i++ ) printf("%d %s %d\n",stu1[i].number,stu1[i].name,stu1[i].age);
} else printf("无法打开文件读取。\n");
} else printf("无法建立文件。\n");
MEND: printf("\n"); system("pause");
}
热心网友
时间:2023-10-14 11:17
把结构体写入文件然后读出【c语言】
用C语言实现。把结构体写入文件,然后再读取出来并显示;
/* structinfile .c
* Auther: tweety
* date: 2009-12-04
*/
#include <stdio.h>
typedef struct Filenode
{
int isempty;
char * data;
}filenode;
int node_init(filenode *node)
{
node->isempty=1;
node->data = "FOOLisENOUGH!";
return 0;
}
int node_write_infile(filenode * node)
{
//把结构体写入文件
FILE *fp=fopen("file.txt","w");
if(fwrite(node,sizeof(Filenode),1,fp))
{
fclose(fp);
return 1;
}
else return 0;
}
int node_read_outfile(filenode *node)
{
//读取结构体
FILE *fp =fopen("file.txt","r");
if(fread(node,sizeof(Filenode),1,fp))
{
fclose(fp);
return 1;
}
else return 0;
}
int main()
{
filenode *innode = malloc(sizeof(filenode));
filenode *outnode =malloc(sizeof(filenode));
node_init(innode);
if(node_write_infile(innode)) printf("file write OK\n");
if(node_read_outfile(outnode))
{
printf("%d\n",outnode->isempty);
printf("%s\n",outnode->data);
}
system("pause");
return 0;
}