写入和读取对象数组 C++ 时出现问题

issue while writing and reading array of objects C++

在写入和读取对象数组时遇到问题,当我也放入和写入数组对象 [0] 和对象 1, it puts object [0] data in object 1 的数据时,我认为他们的许多其他代码问题,如果有人可以的话指导我,我将不胜感激。

#include<iostream>
#include<fstream>
using namespace std;

class A
{
    private:
        int num;
    public:
        void putdata(){
            cout<<"Enter Num: ";
            cin>>num;
            this->num=num;
        }
        void getdata(){
            cout<<"The num is : " << num;
        }
        void ReadFunc(A[],int i);
        void WriteFunc(A[], int i);
};
//
void A :: ReadFunc(A ob1[],int i){
    ifstream R;
    R.open("File9.txt", ios::in | ios :: binary);
    cout<<"\nReading the object from a file : \n";
    R.read( (char *) & ob1[i], sizeof(ob1[i]));
    ob1[i].getdata();
    R.close();
}
void A :: WriteFunc(A ob1[],int i){
    ofstream W;
    W.open("File9.txt", ios::out | ios::app );
    ob1[i].putdata();
    W.write( (char *) & ob1[i], sizeof(ob1[i]));
    W.close();
    cout<<"Congrats! Your object is successfully written to the file \n";
}

int main()
{
    A ob1[100];
      ob1[0].WriteFunc(ob1,0);
      ob1[1].WriteFunc(ob1,1);
      cout<<"\n";
      ob1[0].ReadFunc(ob1,0);
      ob1[1].ReadFunc(ob1,1);
    
    return 0;
}

Output

索引加对象的粗略实现

#include<iostream>
#include<fstream>
using namespace std;

class A
{
    private:
        int num;
    public:
        void putdata(){
            cout<<"Enter Num: ";
            cin>>num;
            this->num=num;
        }
        void getdata(){
            cout<<"The num is : " << num;
        }
        void ReadFunc(A[],int i);
        void WriteFunc(A[], int i);
};
struct A_withIndex { size_t index; A data; };

void A :: ReadFunc(A ob1[],size_t i){
    ifstream R;
    R.open("File9.txt", ios::in | ios :: binary);
    A_withIndex buffer;
    bool found=false;
    while(R){
        R.read( (char *) &buffer, sizeof(buffer));
        if(R.gcount()!=sizeof(buffer)) break;
        if(buffer.index==i){
            found =true;
            obj[i]=buffer.data;
        }
    }
    if(found){
        cout<<"\nReading the object from a file : \n";
        ob1[i].getdata();
    }
    else{
        cout<<"\nObject not found \n";
    }
    R.close();
}

void A :: WriteFunc(A ob1[],size_t i){
    ofstream W;
    W.open("File9.txt", ios::out | ios::app );
    ob1[i].putdata();
    A_withIndex buffer = {i,ob1[i]};
    W.write( (char *) &buffer, sizeof(buffer));
    W.close();
    cout<<"Congrats! Your object is successfully written to the file \n";
}

希望我保留了足够多的完整代码以使其清晰易读。此外,我没有通过编译器 运行 这段代码,因此它可能包含一些错误,例如区分大小写。方法很简单:在读取或写入数据时包含一个索引。

这个实现绝不是高效的,因为它总是追加,即使它可能已经被覆盖并读取整个文件以找到索引处的最后一个。 size_t 也是一个很大的开销。根据索引范围,您可能希望减少到 unsigned char#pragma pack,但如果它那么小,您最好写整个数组。一旦你理解了这个概念,我就会把这些改进留给你。