On-line: гостей 0. Всего: 0 [подробнее..]
Программисты всех стран, объединяйтесь!

АвторСообщение



ссылка на сообщение  Отправлено: 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 .
 

#include <fstream>
#include <iostream>
#include <vector>
#include <string.h>

using namespace std;


typedef struct student
{
char name[10];
int age;
vector<int> grades;
}student_t;

int main()
{
student_t apprentice[3];
strcpy(apprentice[0].name, "john");
apprentice[0].age = 21;
apprentice[0].grades.push_back(1);
apprentice[0].grades.push_back(3);
apprentice[0].grades.push_back(5);

strcpy(apprentice[1].name, "jerry");
apprentice[1].age = 22;
apprentice[1].grades.push_back(2);
apprentice[1].grades.push_back(4);
apprentice[1].grades.push_back(6);

strcpy(apprentice[2].name, "jimmy");
apprentice[2].age = 23;
apprentice[2].grades.push_back(8);
apprentice[2].grades.push_back(9);
apprentice[2].grades.push_back(10);

// Serializing struct to student.data
ofstream output_file("students.data", ios::binary);
output_file.write((char*)&apprentice, sizeof(apprentice));
output_file.close();

// Reading from it
ifstream input_file("students.data", ios::binary);
student_t master[3];
input_file.read((char*)&master, sizeof(master));

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;
}

return 0;
}




Спасибо: 0 
ПрофильЦитата Ответить
Ответов - 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

 
int main()
{
{
student_t apprentice[3];

//...
}


and enclose the second part with the reading operation in its own code block

 
{
student_t master[3];
//....
}

then the program will not work becuase the vectors' elements will be deleted. when the control leaves the first code block.



Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 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

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 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.

Спасибо: 0 
ПрофильЦитата Ответить
Ответ:
1 2 3 4 5 6 7 8 9
большой шрифт малый шрифт надстрочный подстрочный заголовок большой заголовок видео с youtube.com картинка из интернета картинка с компьютера ссылка файл с компьютера русская клавиатура транслитератор  цитата  кавычки моноширинный шрифт моноширинный шрифт горизонтальная линия отступ точка LI бегущая строка оффтопик свернутый текст

показывать это сообщение только модераторам
не делать ссылки активными
Имя, пароль:      зарегистрироваться    
Тему читают:
- участник сейчас на форуме
- участник вне форума
Все даты в формате GMT  3 час. Хитов сегодня: 3
Права: смайлы да, картинки да, шрифты да, голосования нет
аватары да, автозамена ссылок вкл, премодерация откл, правка нет