按照你的逻辑,代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define MAXLEN 1000
typedef struct _st_record {
char szName[60];
char nGender; /* 0--male, 1--female */
unsigned char nAge;
short nBirthYear;
char szDescription[150];
} RRECORD;
//将结构体写入文本文件
void writeFile(FILE* fp, RRECORD t)
{
char buf[100] = { 0 };
sprintf(buf, "Name:%s\n", t.szName);
fwrite(buf, 1, strlen(buf), fp);
if (t.nGender == 0)
sprintf(buf, "Gender:male\n");
else
sprintf(buf, "Gender:femal\n");
fwrite(buf, 1, strlen(buf), fp);
sprintf(buf, "Age:%d\n", t.nAge);
fwrite(buf, 1, strlen(buf), fp);
sprintf(buf, "BirthYear:%d\n", t.nBirthYear);
fwrite(buf, 1, strlen(buf), fp);
sprintf(buf, "Description:%s\n", t.szDescription);
fwrite(buf, 1, strlen(buf), fp);
}
int main()
{
int n = 0; //声明计数用的变量
FILE* fr, *fw; //声明读取和写入的文件指针
RRECORD arr[MAXLEN]; //保存数据
//打开二进制文件
fr = fopen("data.dat", "rb"); //读取二进制文件
if (fr == 0)
{
printf("%s打开失败!\n");
return 0;
}
//打开文本文件
fw = fopen("out.txt", "w");
//读取文件
while (!feof(fr))
{
memset(&arr[n], 0, sizeof(RRECORD));
if (fread(&arr[n], sizeof(RRECORD), 1, fr)) //逐个结构体读取
{
//将结构体写入文本文件
writeFile(fw, arr[n]);
n++; //读取的个数+1
}
}
fclose(fr); //关闭读指针
fclose(fw); //关闭写指针
return 0;
}