There is a program in which fields are entered for each structure from the array, then the entire array is written to a binary file, the question is how to implement the reverse program, that is, to open this file and create a new array from the structures.

#include "stdafx.h" #include<iostream> using namespace std; struct contact { char sname[50]; char number[11]; char adress[50]; }; const int m = 2; int _tmain(int argc, _TCHAR* argv[]) { contact a[m]; for (int i = 0; i < m; i++) { cin >> a[i].sname; cin >> a[i].number; cin >> a[i].adress; } FILE *f; f = fopen("input.dot", "wb"); fwrite(a, sizeof(contact), m, f); fclose(f); system("pause"); return 0; } 
  • one
    You do not know how to read from a file, or create arrays? - Yuriy Orlov
  • Give an example of the code that you have, your question in this form is unclear and it is impossible to answer it - Yuriy Orlov

1 answer 1

C ++ style solution. Since your structure is POD , you can do this:

 #include <fstream> #include <vector> struct Contact { char number[11]; char adress[50]; char sname[50]; }; int main() { // открываем файл на чтение std::ifstream fin("file_name", std::ios::in | std::ios::binary); // здесь будем хранить считанные структуры std::vector<Contact> vec; // временная переменная Contact temp; // пока есть что читать, цикл продолжается while (fin.read((char*)&temp, sizeof(Contact))) { // запихиваем в конец вектора считанную структуру vec.push_back(temp); }; // не забудем закрыть файл fin.close(); } 
  • one
    and then transfer it to 64/32 bits and ... suddenly it breaks. Do not do this. ru.stackoverflow.com/questions/493617/… and there are some nuances. - Monah Tuk
  • @MonahTuk and what in this particular case will break? I just really will not take it - Flowneee
  • one
    No one bothers the compiler to add padings so that the addresses are multiples. The multiplicity of 32 bits - 4 bytes, 64 - 8. Accordingly, the size of the structure will crawl, as a result - the correctness of the read data. In this example, because the byte fields, the compiler will most likely forget and everything will be fine and well (the total size will be 111 bytes). But in general - may not be lucky. What, for example, is the size of this structure: struct Foo {char a; uint64_t b; }; struct Foo {char a; uint64_t b; }; ? Therefore, if we are talking about the proofreading given right into the structure, then we need to apply the package, sacrificing speed. - Monah Tuk