The binary file contains N structures. How to work with these structures - for example, display the fields of each structure on the screen? Structure:

struct Session { char userName[24]; int points; }; 

Fill in the structure:

 void CreateSession() { Session temp; printf_S("\nEnter your name: "); gets_s(temp.userName); temp.points = 0; SaveSessionToFile(temp); } 

Save to file:

 void SaveSessionToFile(Session temp) { ofstream fout("AppData/Sessions", ios_base::binary | ios_base::app); fout.write((char*)&temp, sizeof(Session)); fout.close(); } 

Works great - new data is added to the end of the binary file. But I just can’t figure out how to work with the file now - for example, to output the data of each structure? For example:

 userName1 + points1 // Данные 1 структуры записать в string, вывести string; userName2 + points2 // Данные 2 структуры записать в string, вывести string; userName3 + points3 // Данные 3 структуры записать в string, вывести string; 

I would appreciate the help!

  • You have already been answered, I will add only - 1. There is no need to pass by the value of void SaveSessionToFile(Session temp) , pass as a constant link void SaveSessionToFile(const Session& temp) , and 2. Note that this will work for the simplest structures in the spirit of C - the so-called POD - plain old data. - Harry

1 answer 1

Actually the same as recorded. Create an input file stream in binary mode and write to an instance of the structure.

 Session s; std::ifstream fin("Sessions", std::ios_base::binary | std::ios_base::in); while (fin.peek() != EOF) { fin.read((char*)&s, sizeof(Session)); std::cout << s.userName << " " << s.points << std::endl; } 
  • one
    Only it is necessary to take into account that in the general case it is intolerable, because the alignment in different compilers may vary on different architectures. Therefore, this can be done only when both writing and reading are performed using a program compiled by the same compiler (or fully compatible) - ixSci
  • TheNorthon, thank you so much! - Deco Yo