Отправлено: 25.10.15 12:36. Заголовок: How can i write and ..
How can i write and read a struct to a binary file
Below code i found in internet but its not running it shows error : c4996: strcpy this function or variable may ne unsafe consider using strcpy_s intead .
using namespace std;
typedef struct student
apprentice.age = 21;
apprentice.age = 22;
apprentice.age = 23;
// Serializing struct to student.data
ofstream output_file("students.data", ios::binary);
// Reading from it
ifstream input_file("students.data", ios::binary);
for (size_t idx = 0; idx < 3; idx++)
// If you wanted to search for specific records,
// you should do it here! if (idx == 2) ...
cout << "Record #" << idx << endl;
cout << "Name: " << master[idx].name << endl;
cout << "Age: " << master[idx].age << endl;
cout << "Grades: " << endl;
for (size_t i = 0; i < master[idx].grades.size(); i++)
cout << master[idx].grades << " ";
cout << endl << endl;
Ответов - 3
Отправлено: 01.11.15 14:40. Заголовок: This code is invalid..
This code is invalid.
First of all you should use header <cstring>
instead of <string.h>
Using function strcpy
in this case is not an error. Simply the MS C++ compiler by default considers it like an error. I think the compiler has an option that prevents issueing an error for the function.
The main problem is that the program does not write in the file the data stored in the vectors. It copies the binary image of a vector object itself. This binary image does not include the data allocated by the object itself to store elements of the vector.
The reason by which the program can work is that between the writing to the file and reading from the file the process still keeps the allocated memory.
If for example you place the first part of the program with the writing operation in a separate code block making variable apprentice
local relative to this code block as for example
and enclose the second part with the reading operation in its own code block
then the program will not work becuase the vectors' elements will be deleted. when the control leaves the first code block.
Отправлено: 02.11.15 09:39. Заголовок: Plz show me how to w..
Plz show me how to write and read from a binary file one by one through a for loop
I tried but error. I tried to understand binary saving from internet when i run the example file I stuck with some error . I need a. Proper example to learn
1, how to access a particular point
2, how to access sequence
3,how to change a particular point
4 how to remove a particular point
Отправлено: 02.11.15 12:20. Заголовок: You have a sequentia..
You have a sequentially accessed file with variable length records provided that the vector may contain various nhumbers of elements.
In this case you should before each record place in the file the record size and then read the records in two steps: at first you read the record size and then the record itself.
If you need the direct access to the records then you should use a DMS.