A lot of questions about binary (writting, reading, etc.)

So I have a problem with, as the title says, binary fstream.
As in the code down there, here are my questions:

1. How to write in a user defined char array (only had experience with only int numbers)?

2.How to read from a binary file?

3.How to search a binary file for example, like in the code down there, sex of a student?
Thank you.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <fstream>
using namespace std;

struct Student{
	char name[20];
	char last[20];
	char sex;
};

int main()
{
	int a=1;
	while (a!=0)
	{
		cout<<"1. Type into hte file."<<endl;
		cout<<"2. print from the file."<<endl;
		cout<<"3. print male students."<<endl;
		cout<<"4. print female students."<<endl;
		cout<<"0. exit."<<endl;
		cin>>a;
		
		if (a==1)
		{
			Student s;
			fstream d;
			d.open("studenti.dat", ios_base::out| ios_base::binary|ios_base::app);
			cout<<"Name:"<<endl;
			cin>>s.ime[20];
			d.write ((char*)s.name, sizeof(s.name));
			cout<<"Last name:"<<endl;
			d.write ((char*)s.last, sizeof(s.last));
			cout<<"Sex (M for male, F for female):"<<endl;
			cin>>s.sex;
			if (s.sex=='M' || s.sex=='F')
			{
				d.write((char*)&s.sex, sizeof(s.sex));
			}
			else
			{
				cout<<"It has to be M or F"<<endl;
			}
			d.close();
		}
		
		else if (a==2)
		{
			char sex;
			fstream d;
			d.open("studenti.dat", ios_base::in|ios_base::binary);
			d.seekg(0, ios_base::beg);
			d.read((char*)&sex, sizeof(sex));
			cout<<spol<<endl;
			d.close();
		}
		
		else if (a==3)
		{
			cout<<"The program will print male students."<<endl;
			fstream d;
			d.open("studenti.dat", ios_base::in|ios_base::binary);
			d.seekg(0, ios_base::beg);
		}
		
		else if (a==4)
		{
			cout<<"The program will print male students female students."<<endl;
			fstream d;
			d.open("studenti.dat", ios_base::in|ios_base::binary);
			d.seekg(0, ios_base::beg);
			d.close();
		}
		
		else
		{
			cout<<"It has to be a number between 0-4."<<endl;
		}
	}
	return 0;
}
Last edited on
I really find your code difficult to read, with all the single letter variables and runtogetherlines and such. So I recommend you re-work your code and use meaningful variable names.

I also suggest you open your file once before the loop, and don't forget to test the stream to insure it opened correctly. You are using a fstream so you can use it for both reading and writing.

d.write ((char*)s.name, sizeof(s.name));
In the above snippet name is already a char* so you don't need the cast. Also if you do need to cast you should use the C++ style casts like static_cast<int> variable instead of the unsafe C style casts.

You may want to study up on those standard functions: http://www.cplusplus.com/reference/ostream/ostream/write/
Topic archived. No new replies allowed.