C++如何读入一个文件中的结构体数组数据?

比如一个文件中存储了结构体数组code[100],结构体里有三个整型变量,现在我打开这个文件希望将code[N]读入到同样定义的结构体test中,我该如何读入?
FILE* pRF;
pRF = fopen("hbin.txt","rb");
instruction i; // instruction register
int num=0;
while (1)
{
fread(&i,sizeof(instruction),1,pRF);
if ( ferror(pRF) )
{
fclose(pRF);
perror("读文件过程中失败!");
return ;
}
if ( feof(pRF) )
{
break;
}
code[num] =i;
num++;
}
找了个简单的办法

取决于文件中数据的存储方式。
1 如果文件中存储的方式为二进制形式数据:
需要使用fread(C语言风格)或ifsteam的read成员函数(C++风格。)从文件中读取结构体数据到对应的结构体指针上。
如
struct test
{
int a;

};
struct test t;
fread(&t, 1,sizeof(t), fp);
或
file.read(&t, sizeof(t));
2 如果文件中,是以文本方式存储的可读的结构体数据:
需要根据文件中数据的存储格式,通过fscanf(C语言风格)或ifstream的>>成员函数,读取各个值到对应的结构体成员变量中。
如 struct test t;
fscanf(fp, "%d",&t.a);
或
file>>t.a;
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-07-10
#include <iostream>
using namespace std;
typedef struct hardware{
int num;
int amount;
int price;
}instruction;
int main()
{
instruction code[100] = {0};
for ( int j=0; j < 100; ++j )
{
code[j].amount += j*2;
code[j].num += j*4;
code[j].price += j*8;
}

FILE* hbin = fopen("hbin.txt", "w");
for (j = 0; j < 100; j++)
fwrite(&code[j], sizeof(instruction), 1, hbin);
fclose(hbin);

ifstream iFile("hbin.txt", ios::binary);
if ( !iFile )
{
cout<<"open file error!"<<endl;
return -1;
}
iFile.seekg(0,ios::end);
int iFileSize = iFile.tellg();
iFile.seekg(0,ios::beg);
char* psbBuf = new char[iFileSize];
memset(psbBuf, 0, iFileSize);
iFile.read(psbBuf,iFileSize);
instruction* pware = (instruction*)psbBuf;
instruction ac[100] = {0};

for ( int i =0; i < iFileSize/sizeof(instruction); ++i)
{
ac[i].amount=pware->amount;
ac[i].num=pware->num;
ac[i].price=pware->price;
cout<<ac[i].amount<<endl;
++pware;
}
return 0;
}本回答被提问者和网友采纳
第2个回答  2012-07-10
和这个差不多啊,主要是把fwrite换成fread

二进制,fopen的参数,要加上b
写成FILE *fp = fopen("hbin.txt", "rb");
否则读不完整
第3个回答  2012-07-10
这个没有捷径..
1.你可以用正则表达直接匹配。
2.需要你自己按行解析了。
第4个回答  2012-07-10
1.
FILE *hbin = fopen("hbin.txt", "r");
fread(code, sizeof(instruction), 100, hbin);
fclose(hbin);
相似回答