简体   繁体   English

如何将结构数组写入二进制文件并再次读取?

[英]how can i write an array of structures to a binary file and read it again?

I'm writing an array af structures(factor is a structure) to a binary file like this: 我正在将数组af结构(factor是一个结构)写入二进制文件,如下所示:

factor factors[100];

ofstream fa("Desktop:\\fa.dat", ios::out | ios::binary);
fa.write(reinterpret_cast<const char*>(&factors),sizeof(factors));

fa.close();

and I run the program and save 5 records in it.in another file, I want to read the structures so I wrote this: 然后运行该程序并在其中保存5条记录。在另一个文件中,我想读取结构,所以我这样写:

    int i=0;
ifstream a("Desktop:\\fa.dat", ios::in | ios::binary);

factor undelivered_Factors[100];

    while(a && !a.eof()){
        a.read(reinterpret_cast<char*>(&undelivered_Factors),sizeof(undelivered_Factors));
        cout<<undelivered_Factors[i].ID<<"\t"<<undelivered_Factors[i].total_price<<endl;
        i++;
    }
    a.close();

but after reading and printing the saved factors it inly reads and shows the firs 2 of them in the array.why?what should i do? 但是在读取并打印保存的因子后,它会间接读取并在数组中显示它们的第2个。为什么?我该怎么办?

Second parameter of ofstream::write and ::read is size of written memory in bytes (aka 'char' in C\\C++), which is right - you're writing entire array at once. ofstream :: write和:: read的第二个参数是写入内存的大小(以字节为单位) (在C \\ C ++中为“ char”),这是正确的-您要一次写入整个数组。 In reading procedure you had mixed up an per element and array processing. 在阅读过程中,您将每个元素和数组处理混合在一起。 You expect to read whole array, then you print one value, then you read another 100 of records which you do not have in file, I presume. 我想,您希望读取整个数组,然后打印一个值,然后再读取文件中没有的另外100条记录。 also eof() happens only when you attempt to read and it failed. eof()也仅在您尝试读取但失败时才会发生。 If you stand on end of file,eof() isn't triggered, that's why you get two records printed. 如果您站在文件末尾,则不会触发eof(),这就是为什么要打印两个记录的原因。

You are doing complete read in the single call so your loop runs only one time hence it will output only first struct value. 您正在一次调用中完成完全读取,因此循环仅运行一次,因此它将仅输出第一个结构值。 Change your while loop like this: 像这样更改while循环:

if(a)
{
   a.read(reinterpret_cast<char*>(&undelivered_Factors),sizeof(undelivered_Factors));
}
for(int i=0; i<100; ++i)
{
   cout<<undelivered_Factors[i].ID<<"\t"<<undelivered_Factors[i].total_price<<endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM