struct user{
char name[25];
int level;
double grade;
char password[10];}
and i want to write to a file with this function. but it work for a one type of struct i want save array of my top struct
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));
}
I would suggest you store your user
structs in a std::vector
and define another function like this (just one example of several alternatives):
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
}
}
This will iterate over the whole vector of users and save each one of them. However, don't ignore the comment from deviantfan above - you can very easily get into trouble when saving data to a file the way you're doing it, especially since you'll want to read these things back.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.