files and streams

Can someone explain write to it part of the program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 const int MAX = 100; //size of buffer
int buff[MAX]; //buffer for integers

int main()
{
 for(int j=0; j<MAX; j++) //fill buffer with data
		buff[j] = j; 
	
	//create output stream
	ofstream os("edata.dat", ios::binary);
	
	//write to it
	os.write( reinterpret_cast<char*>(buff),MAX*sizeof(int) );
	os.close(); 

}
line 13 particularly
Hi,
// os.write( reinterpret_cast<char*>(buff),MAX*sizeof(int) );

The first parameter of os.write() is the variable you that you stored data in it and you want to write that data to the file.

**Another way of implementing the write function:
os.write( (char*)&buff, MAX*sizeof(int));

The Second parameter of os.write() is how many bytes it should write to the file. sizeof(int) most of the times gives you 4 and max is 100 so you are writing 400 bytes to the file.
Because you have an array of 100 integers and each integer is 4 bytes.

Example:
- Suppose you want to write an integer for example 7 to the file!
then your program should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
    int number = 7;

    // Open the file
    ofstream os("myfile.bin", ios::binary); 
    // ofstream os("myfile.txt"); would do the same job!

    // Write to the file
    os.write((char*)&number,sizeof(int)); 

    // Close the file
    os.close();


    return 0;
}


That's it,
I hope my explanation was clear to you.

Good luck.
Two confusions shouldn't myfile.bin have 7 stored in it instead it has a strange different output another problem is the data type is of int but in the first argument its pointer to char and than the variable name will always be a pointer of char
The key to understanding all of this is the line here:
ofstream os("edata.dat", ios::binary);
The output file is opened in binary mode.

What is written to the file is the raw contents of the memory where the variables are stored. The exact output can vary depending on the type of computer system on which the program is compiled and run.

The second example gives, in hexadecimal representation, these four bytes when I run it: "07 00 00 00"

Two things to note: the actual number of bytes may vary, depending on the computer system, it could be 2, 4 or 8 bytes for example, and the actual order of the bytes can vary depending on the processor type, what is known as endian-ness. Thus the data could perhaps be "00 00 00 07" instead.

If you are using Windows, a hex editor such as HxD can be useful for working with binary files. (for human beings, hexadecimal is more convenient to work with than pure binary). http://mh-nexus.de/en/hxd/
Last edited on
closed account (G30GNwbp)
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
#include <iostream>
#include <fstream>

int main()
{

    using std::cout;

    int number = 7;

    // Open the file
    std::ofstream os("myfile.bin", std::ios::binary); 
    // ofstream os("myfile.txt"); would do the same job!

    // Write to the file
    os.write((char*)&number,sizeof(int)); 

    // Close the file
    os.close();


    std::ifstream is("myfile.bin", std::ios::binary); 
    char* buffer = new char[sizeof(int)];
    is.read (buffer,sizeof(int));

    int wilson = static_cast<int> (*buffer);
    cout <<  wilson << std::endl;

    return 0;
}



if ios::bin gives output in binary changing it to ios::dec , shouldn't changing it give output in decimal but it doesn't what if want output in it's given current input form with no changes in it

Another problem is changing the name of folder doesn't make a new file of .txt or .bin any sort of file even building a solution and than debugging it again

and in example 2 my output is []
and is it syntax to write
os.write((char*)&number,sizeof(int))
where char* should be always written irrevelant to datatype used for variables
The file open mode can use a combination of these flags:
in, out, binary, ate, app, trunc
http://www.cplusplus.com/reference/fstream/ofstream/open/
Notice that ios::dec is not one of the available options. The opposite of "binary" in this context is "text", and text mode is specified simply by omitting ios::binary.

what if want output in it's given current input form with no changes in it
Your question is not entirely clear. However it can be argued that a binary file is already the data in its current form with no changes.

If you want the output to be a text file containing decimal numbers, you could do this:
1
2
3
    ofstream out("output.txt");
    int number = 7;
    out << number;

However, this statement out << number involves an automatic conversion of the integer to a series of ascii characters in decimal format, so it involves changing the data considerably.

Another problem is changing the name of folder doesn't make a new file of .txt or .bin any sort of file even building a solution and than debugging it again
sorry I'm not understanding what this means exactly.


and in example 2 my output is []
But that is not very meaningful. What was the file contents when you viewed it in hexadecimal?



Last edited on
However it can be argued that a binary file is already the data in its current form with no changes.

than why do i get a change output in the age variable in the following code
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
class person
{
private:
	char name [20];
	int age;
public:
	void showdata()
	{
		cout<<"NAME : "<<name<<endl;
		cout<<"AGE : "<<age<<endl;
	}
	void getdata()
	{
		cout<<"NAME :";
		cin>>name;
		cout<<"AGE : ";
		cin>>age;
	}
};

int main()
{
person p;
fstream file;
char choice;
file.open("DATA1.txt",ios::app | ios::out | ios ::in | ios::binary);
do
{
	cout<<"Enter data\n";
	p.getdata();
	file.write(reinterpret_cast<char*>(&p),sizeof(p));
	cout<<"Enter choice\n";
	cin>>choice;
}
while (choice=='y');

	getch();

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 int number = 7;

    // Open the file
    ofstream os("myfile.bin", ios::binary); 
    // ofstream os("myfile.txt"); would do the same job!

    // Write to the file
    os.write((char*)&number,sizeof(int)); 

    // Close the file
    os.close();


    return 0;

its output is nothing i meant output of myfile.bin is almost like [] where the ends are joined together
What was the file contents when you viewed it in hexadecimal?

No changes are made exact this code is written isn't this in binary
Last edited on
Quick example of binary input and output:
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
#include <fstream>
#include <iostream>
using namespace std;

class person
{
private:
    char name [20];
    int age;
public:
    void showdata()
    {
        cout<<"NAME : "<<name<<endl;
        cout<<"AGE : "<<age<<endl;
    }
    void getdata()
    {
        cout<<"NAME :";
        cin>>name;
        cout<<"AGE : ";
        cin>>age;
    }    
    void putdata()
    {
        cout << "Name: " << name
             << " Age: " << age
             << endl;
    }
};


void create_file(char * fname);
void read_file(char * fname);

int main()
{
    char filename[] = "data.bin";
    
    cout << "input the data" << endl;
    create_file(filename);
    read_file(filename);
    
    return 0;
}

void create_file(char * fname)
{
    person p;
    
    ofstream file(fname, ios::binary);
    char choice;
    
    do
    {
        cout<<"Enter data\n";
        p.getdata();
        file.write(reinterpret_cast<char*>(&p),sizeof(p));
        cout<<"Continue y/n\n";
        cin>>choice;
    }
    while (choice=='y' || choice == 'Y');
    
}

void read_file(char * fname)
{
    person p;
    
    ifstream file(fname, ios::binary);
    
    while (file.read(reinterpret_cast<char*>(&p),sizeof(p)) )
    {
        p.putdata();
    }
        
}
Last edited on
I assume from the previous responses that you have not actually viewed the file contents using software which can display the hexadecimal values. If you intend to work with binary files, this is an essential tool.
closed account (G30GNwbp)
Sharan forgive me for asking but I just want to make sure you understand.

Do you know what a byte is?

Do you know what a bit is?

Do you understand that in hexadecimal FF is a number and in binary it could be represented with 8 bits? "FF" in hex, in binary as "11111111", and in decimal as 255.

You understand that you cannot see with your eyes how your computer stores the number 7? All you can ever see with your eyes is an abstract representation of how 7 is stored.
Last edited on
rtd2645 i completely understand all number system concept of bin hex octa etc.I guess i misunderstand that i could view how 7 is stored .

why does this show run time error
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
81
82
83
84
85
#include <fstream>
#include <iostream>
#include<conio.h>
#include<string>
using namespace std;

class Employee
{
private:
	string name;
	string id;
	float salary;
public:
	Employee()
	{
		name="0";
		id="0";
		salary=0;
	}
	Employee(string name1,string id1,float salary1)
	{
		name=name1;
		id=id1;
		salary=salary1;
	}
	void set(string  name1,string id1,float salary1)
	{
		name=name1;
		id=id1;
		salary=salary1;
	}
	void get()
	{
		cout<<"Enter Data : \n";
		cout<<"Enter name :\n";
		cin>>name;
		cout<<"Enter id : \n";
		cin>>id;
		cout<<"Enter salary : \n";
		cin>>salary;
	}
	void display()
	{
		cout<<"Name : "<<name<<endl;
		cout<<"Salary : "<<salary<<endl;
		cout<<"ID : "<<id<<endl;
	}
	

};
void create(char *fname)
	{
		char choice;
		Employee temp;
		ofstream file(fname,ios::app|ios::out|ios::binary|ios::in);
		do
	{
		temp.get();
		file.write(reinterpret_cast<char*>(&temp),sizeof(temp));
		cout<<"Press Y or y to continue or any other key to exit\n";
		cin>>choice;
	}
	while(choice=='y' || choice=='Y');
}
void read(char *fname)
{
	Employee temp;
	ifstream file(fname,ios::app|ios::out|ios::binary|ios::in);
	while(file.read(reinterpret_cast<char *>(&temp),sizeof(temp)))
	{
		temp.display();
	}
}


int main()
{
	char name[20]="LAB13.txt";
	create(name);
	read(name);
	return 0;
}



You will run into problems trying to use a simple binary file of an object containing complex objects such as std::string. That's because the actual data for the string is not contained within the object itself. Instead, there will be a pointer containing the address of the text itself. But saving the address to a file is meaningless, as when the file is read back in, the memory location will no longer be valid.

If your Employee class uses a plain character array for the name and id, it should work. Alternatively, you will have to write different code for both writing the object to the file and reading from the file in order to handle the actual text of the strings.
Thank you so much all of you :)
After changing string into char i get this output
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
Enter Data :
Enter name :
s
Enter id :
1
Enter salary :
1
Press Y or y to continue or any other key to exit
n
Name : áC·
Salary : -1.07374e+008
ID : ☺
Name : ╠╠╠╠╠╠╠╠☺
Salary : -1.07374e+008
ID :
Name : ☺
Salary : -1.07374e+008
ID : ╠╠╠╠╠╠╠╠╠╠╠╠☺
Name :
Salary : -1.06955e+008
ID : ╠╠╠╠☺
Name : ╠╠╠╠╠╠╠╠╠╠╠╠☺
Salary : -1.07374e+008
ID : ╠╠╠╠
Name : ╠╠╠╠☺
Salary : 2.10195e-044
ID : 1
Name : ╠╠╠╠
Salary : 1.48099e-038
ID : ╠╠╠╠╠╠╠╠☺
Name : 1
Salary : -1.07374e+008
ID : ☼
Name : ╠╠╠╠╠╠╠╠☺
Salary : 1.4013e-045
ID : ΦC2☺1
Name : ☼
Salary : -1.07374e+008
ID : ╠╠╠╠╠╠╠╠╠╠╠╠☺
Name : ΦCC
Salary : -1.06956e+008
ID : ☺
Name : ╠╠╠╠╠╠╠╠╠╠╠╠☺
Salary : -1.07374e+008
ID : ╠╠╠╠ΦCC
Name : ☺
Salary : 2.10195e-044
ID : s
Name : ╠╠╠╠ΦC╫
Salary : -1.06956e+008
ID : ╠╠╠╠☺
Name : ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠1
Salary : -1.06956e+008
ID : ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Name : ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠1
Salary : -1.06956e+008
ID : ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Name : ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠1
Salary : -1.06956e+008
ID : ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Name : ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠1
Salary : -1.06956e+008
ID : ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
Name : ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠1
Salary : -1.06956e+008
ID : ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
It depends what exact changes you have made. I took the code posted earlier, changed the code like this:
old:
1
2
3
    string name;
    string id;
    float salary;
new:
1
2
3
    char name[20];
    char id[20];
    float salary;

But of course doing that necessitates various other changes.
old:
1
2
3
4
5
6
    Employee()
    {
        name="0";
        id="0";
        salary=0;
    }
new:
1
2
3
4
5
6
    Employee()
    {
        strcpy(name, "0");
        strcpy(id, "0");
        salary=0;
    }

and so on...
Then the code should work.
Topic archived. No new replies allowed.