Advertisement
Timtsa

save struct to the file

Jan 9th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <stdio.h> // для FILE
  2. #include <string>
  3.  
  4. struct  Data {
  5.     std::string str;
  6.     double *val;
  7. };
  8.  
  9. int main() {
  10.     Data *primary = new Data;
  11.     primary->str = "TEST";
  12.     primary->val = new double(99.99);
  13.     FILE *fp;
  14.     fp = fopen("buf.txt", "w");
  15.     fwrite(primary, sizeof(Data), 1, fp); // запись.
  16.     fseek(fp, 0, SEEK_END); // смещение в конец.
  17.     fwrite(primary->val, sizeof(*primary->val), 1, fp); // запись содержимого указателя.
  18.     fclose(fp);
  19.  
  20.     Data *secondary = new Data;
  21.     fp = fopen("buf.txt", "r");
  22.     fread(secondary, sizeof(Data), 1, fp); // чтение.
  23.     secondary->val = new double; // выделяем новую память.
  24.     fseek(fp, sizeof(Data), SEEK_SET); // смещение к началу содержимого указателя.
  25.     fread(secondary->val, sizeof(*secondary->val), 1, fp); // чтение содержимого указателя.
  26.     fclose(fp);
  27.  
  28.     // Проверка:
  29.     if (std::strcmp(primary->str.c_str(), secondary->str.c_str()) == 0
  30.         && *primary->val == *secondary->val)
  31.     {
  32.         // Ура! Все сошлось.
  33.         return 0;
  34.     }
  35.     else {
  36.         return 1;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement