如何使用指针发送结构数组

how to send array of struct with pointer

本文关键字:结构 数组 何使用 指针      更新时间:2023-10-16
struct user{
char name[25];
int level;
double grade;
char password[10];}

我想用这个函数写入一个文件。但它适用于一种类型的结构我要保存我的顶部结构的数组

void writeusertofile(user u){
fstream of("user.dat",ios::out|ios::app|ios::binary);
if(of.is_open()){
    of.write((char*)&u.level,sizeof(int));
    of.write((char*)&u.grade,sizeof(double));
    of.write((char*)&u.name,25*sizeof(char));
    of.write((char*)&u.password,10*sizeof(char));
}

我建议您将user结构存储在std::vector中,并定义另一个这样的函数(只是几种替代方案的一个例子):

void write_all_users_to_file(const std::vector<user>& v)
{
    //open file, check it's OK
    //write the number of user records you're saving, using v.size()
    for(auto& u : v)
    {
        //do your of.writes
    }
}

这将遍历用户的整个向量并保存每个用户。但是,不要忽略上面deviantfan的评论 - 在以您的方式将数据保存到文件中时,您很容易遇到麻烦,特别是因为您需要回读这些内容。

void writeusertofile(user u[],size_t s){
    fstream of("user.dat",ios::out|ios::app|ios::binary);
    for(int i=0;i<s;++i){
        of.write(reinterpret_cast<const char*>(&u[i]),sizeof(user));
    }
}
int main(){
    user u[3]={
        {"theName",3,55.3,"pwd"},
        {"theName2",2,74.2,"pwd2"},
        {"theName3",7,24.6,"pwd3"}
    };
    writeusertofile(u,3);
    return 0;
}