Hello! I have two structures:

struct Student { char Name[20]; char Surname[20]; int Age; char Phone[20]; char Address[20]; }; struct ArrayStudents { Student **PtrSt; int Size; int Count; int Block; }; 

How can you write a structure to a file using only the fwrite () function, so that you can later load this data through fread ().

  • First, decide on the title and labels. So far your question has nothing to do with C ++. Secondly, specify what exactly is not clear for you. How does fwrite() ? See in the description of your library, or man fwrite . How to write with fread() ? It's simple: no way, fread() doesn't write anything in principle. - user6550
  • It turns out that the main structure of ArrayStudents is written to a file, but there is a second Student structure in it which is not recorded. And therefore when I load data through fread, then instead of the data of the second structure there is garbage. - Lightness
  • Do you really think that here is a telepathic community, and everyone already knows exactly how and what you are doing? (if the hint is not understood - show the code) - user6550

1 answer 1

If you do to warm up, you can decide that you are writing the ArrayStudents structure to the file and expect that this will entail an automatic recording of the data pointed to by the PtrSt field. But it is not. Try to look at the created structure in the debugger (memory dump mode), draw on a piece of paper (with your hands! Pen, pencil ...) the memory allocation when initializing such a structure and adding students to it. It will become clear that 1) students need to be recorded separately and 2) the entire structure of ArrayStudents is not necessary to record.

For example, the entry:

 struct ArrayStudents students; /* ... добавили студентов ... */ fwrite( &students.Count, sizeof(students.Count), 1, file ); for( int i = 0; i < students.Count; i++ ) { fwrite( students.PtrSt[i], sizeof(struct Student), 1, file ); } 

Reading:

 int Count; fread( &Count, sizeof(Count), 1, file ); /* ... создали структуру ArrayStudents на Count студентов ... */ for( int i = 0; i < Count; i++ ) { fread( students.PtrSt[i], sizeof(struct Student), 1, file ); } 
  • Thanks, saving to the file works, but here is the loading problem. On this line, knocks out the error fread (a.PtrSt [i], sizeof (Student), 1, f1); void LoadContacts (ArrayStudents & a) {system ("cls"); FILE * f1 = nullptr; char filename [MAX_PATH] = "Contacts.txt"; fopen_s (& f1, filename, "rb"); if (f1 == NULL) {perror ("Error:"); return; } a.Count = _filelength (_fileno (f1)) / sizeof (Student); fread (& a. Count, sizeof (a. Count), 1, f1); for (int i = 0; i <a.Count; i ++) {fread (a.PtrSt [i], sizeof (Student), 1, f1); } fclose (f1); RussianMessage ("File uploaded! \ N"); _getch (); } - Lightness
  • So read the error message, what do they write? In addition, the logic again has a problem (why are you reading a. Count, if you determine how many records there are by file length?) - user6550