Hello guys, just getting into reading/writing to a file using the ofstream in c++. Even though I am successful in doing so and reading back from the file is ok, the file itself when viewed in windows explorer is over 300mb large!
And this was after I entered less text to store into the file. Originally it ended up being 1.12 gb large! :O
I am puzzled at the size, so I am hoping someone can point out what I am doing wrong. The following code is just a sample program to test the file writing/reading after researching the net.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
usingnamespace std;
struct employee
{
int id;
string name;
int age;
string address;
} emp;
main()
{
ofstream file("employer.dat", ios::out|ios::binary);
if (!file)
{
cout << "Error opening file, creating a new file\n";
file.clear();
file.open("employer.dat", ios::out|ios::binary);
}
try
{
cout<<"Enter your id # ";
cin>>emp.id;
cout<<"Enter your name ";
cin.ignore();
getline(cin,emp.name);
cout<<"Enter your age ";
cin>>emp.age;
if(emp.age <=0)
throw emp.age;
cout<<"Enter your address ";
cin.ignore();
getline(cin,emp.address);
}
catch(int e)
{
cout << e << " Sorry this age is not acceptable\n";
Sleep(5);
exit(1);
}
file.seekp((emp.id * sizeof(emp)), ios::beg);
file.write(reinterpret_cast<char*>(&emp),sizeof(emp));
file.close();
ifstream fin("employer.dat", ios::in|ios::binary);
cout<<"Enter the employee id you want to view ";
cin>>emp.id;
fin.seekg((emp.id * sizeof(emp)), ios::beg);
fin.read(reinterpret_cast<char*>(&emp),sizeof(emp));
cout<<"Id is ";
cout<<emp.id<<endl;
cout<<"Name is ";
cout<<emp.name<<endl;
cout<<"Age is ";
cout<<emp.age<<endl;
cout<<"Address is ";
cout<<emp.address<<endl;
fin.close();
system("pause");
}
The output is below:
Enter your id # 20006348
Enter your name doc archy
Enter your age 30
Enter your address 7 bird street
Enter the employee id you want to view 20006348
Id is 20006348
Name is doc archy
Age is 30
Address is 7 bird street
Press any key to continue . . .
The file with the above data, ended up being 306mb large.
LowestOne is right in that line 53 is the problem. All the bytes you skip by doing seekp will be part of the total file size. If it actually takes up all that space on the hard disk depends on you OS.
Another problem with your code is that you can't write an std::string to file like that. Internally std::string contains a pointer to the actual string data but only the pointer value will be written to the file.