473,666 Members | 2,069 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

classes wrting/reading to binary file

Hi all,

[code snippet appended at the end.)
my question:
A class has a few string variables with not know length at design
time.

Now I declare lets say a 1000 of those classes and put them in a vector.

Can I write that vector directly to a binary file?
(.wright((char *)&vector,sizeo f (vector)))

Currently I write the classes to the file (iterate over the vector).
As a safety I write the length of the variable strings before the class
so that when I read the file I can create a string thats large enough,
using: .resize(length_ of_string,'\0')

The code that I wrote works. If I leave a function out namely
files.clear();C ould someone explain why it breaks?
Improvement on the code itself is always welcome.

My system:Linux 2.6 gnu compiler.
This is the code snipped that I wrote:
FileDes is the class with three strings (declared as "string")
the normal members functions are present get*data*, set*data*, operator<*>,...

ItsFile is declared as fstream in the class datafile (again a class with
normal member functions.)

void
datafile::ReadF romFile (vector < FileDes > &vecfd)
{
FileStatus (input, open); // opens a file in binary mode for input
int length, a, b, c;
//read the size of the vector.
//why? so only one (re)allocation is needed
ItsFile.read ((char *) &length, sizeof length);
vecfd.reserve (length);
for (int i = 0; i < length; i++) //reading from a file
{

//read the length of the 3 strings first:
ItsFile.read ((char *) &a, sizeof a);
ItsFile.read ((char *) &b, sizeof b);
ItsFile.read ((char *) &c, sizeof c);
FileDes temp(a,b,c) ; //expand strings to hold enough data
FileDes temp; //works also. does string expand automatically
//in this situation(or code)

//read the class and add to the vector
ItsFile.read ((char *) &temp, sizeof temp);

//if the program breaks it happens on the next line:
vecfd.push_back (temp);

}

}

int
main ()
{
datafile Filed;
int length;
vector < FileDes > files;
vector< FileDes > filesa;
Filed.GetFileLi st (files);
Filed.WriteToFi le (files);
//The above all works fine checked it with displaying the strings when
//I knew what it had to contain

files.clear();//if left out the program works.
//if present it breaks at run time,
// executing the next line of code.
//break point in void datafile::ReadF romFile... at vecfd.push_back (temp);

Filed.ReadFromF ile (filesa);

/*

DO SOME STUFF
*/
return 0;
}
Jul 22 '05 #1
4 3150
On Thu, 01 Jan 2004 07:52:26 +0000, nightflyer wrote:
Hi all,

[code snippet appended at the end.)
my question:
A class has a few string variables with not know length at design
time.

Now I declare lets say a 1000 of those classes and put them in a vector.

Can I write that vector directly to a binary file?
(.wright((char *)&vector,sizeo f (vector)))


No, and this seems also to be why your program breaks. It seems you try
to modify string objects directly or something like that. You cannot just
stream out a class and hope it works. It doesn't. It only works for PODs
(search google on that) and then only if the POD does not contain
pointers. Both the string and the vector class break both rules.

Besides, even for the cases where it does work, it only works when the
receiver has the same binary layout as the sender. This often is not very
important, but it becomes /very/ important when this problem occurs on a
network connection. Same problem, different context only.

What you have to do is what you already did for the vector class. Stream
out using your own data format. A text-only format often works very well
(diskspace is cheap) and is very practical. But binary is possible as well
and much easier to program.

[ As an aside, you may want to take a look at XML libraries, they simplify
these kind of problems considerably, if at the price of a steep learning
curve. ]

Streaming out a string could be done something like this (errorchecking
omitted):

void so(std::ostream o, const std::string &s) {
size_t len = s.size();
o.write(reinter pret_cast<const char *>(&len), sizeof(len));
o.write(s.c_str (), len);
}

Reading back in is slightly trickier, we are not allowed to modify what
c_str() points to, nor can we assume safely we can use &s[0] as a pointer
to a continous array, so we use an intermediary to hold the contents of
the string:

void si(std::istream i, std::string &s) {
size_t len;
i.read(reinterp ret_cast<const char *>(&len), sizeof(len));
vector<char> v(len);
i.read(&v[0], len);
s = string(v.begin( ), v.end());
}

This code is untested, may contain bugs, may contain big errors. But you
probably get the basic idea.

It also might be a good idea to insert some markers in the stream for
better error checking. A magic number (signature) and version at the start
of the file are probable the least, but also sufficient for your problem.
When reading the file back, you check to see if the magic number is there
(high probablility the file was actually written by your program) and
check the version number (what version of the data-layout in the file are
we using, don't use program version number here).

HTH,
M4

Jul 22 '05 #2
On Thu, 01 Jan 2004 15:24:52 +0100, Martijn Lievaart wrote:
void so(std::ostream o, const std::string &s) {
void so(std::ostream & o, const std::string &s) {
void si(std::istream i, std::string &s) {


void si(std::istream & i, std::string &s) {

Oops.

M4

Jul 22 '05 #3
On Thu, 01 Jan 2004 16:06:29 +0100, Martijn Lievaart wrote:
On Thu, 01 Jan 2004 15:24:52 +0100, Martijn Lievaart wrote:
void so(std::ostream o, const std::string &s) {


void so(std::ostream & o, const std::string &s) {
void si(std::istream i, std::string &s) {


void si(std::istream & i, std::string &s) {

Oops.

M4


In void si(...):
i.read(reinterp ret_cast<const char *>(&len), sizeof(len));

change to:
i.read(reinterp ret_cast< char *>(&len), sizeof(len));

know it works.
thanks a lot for the help.
Jul 22 '05 #4
On Thu, 01 Jan 2004 19:46:25 +0000, nightflyer wrote:
In void si(...):
i.read(reinterp ret_cast<const char *>(&len), sizeof(len));

change to:
i.read(reinterp ret_cast< char *>(&len), sizeof(len));


Ahhh, damn! Next time I'll compile the stuff first.... :-)

Glad to be of service.

M4

Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
6412
by: john smith | last post by:
Hi, I have a file format that is going to contain some parts in ascii, and some parts with raw binary data. Should I open this file with ios::bin or no? For example: filename: a.bin number of points = 123 @@@begin data@@@ gibberish follows.....
50
4932
by: Michael Mair | last post by:
Cheerio, I would appreciate opinions on the following: Given the task to read a _complete_ text file into a string: What is the "best" way to do it? Handling the buffer is not the problem -- the character input is a different matter, at least if I want to remain within the bounds of the standard library.
7
6055
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should populate a series of structures of specified variable composition. I have the structures created OK, but actually reading the files is giving me an error. Can I ask a simple question to start with: I'm trying to read the file using the...
2
1975
by: Jacek Dziedzic | last post by:
Hello! Suppose I have a class that contains only public members of builtin types and a default constructor. Because of the default constructor it is no longer an aggregate and therefore no longer POD, according to my understanding of http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html I need to be able to serialize this class to/from a binary file
30
4570
by: siliconwafer | last post by:
Hi All, I want to know tht how can one Stop reading a file in C (e.g a Hex file)with no 'EOF'?
4
1287
by: joey.powell | last post by:
I am writing a class that will do some binary file IO. The class will need to read a header from the binary file, and it will also need to read a varying number of records in the file. I currently have two main methods: Open(string FilePath) and Close(). I would like to read all of the data into variables whenever Open is called. I would like to have a Header (sub?)class within the main class, and maybe a collection or array for the...
6
5261
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
9
9869
by: Use*n*x | last post by:
Hello, I have a binary file (image file) and am reading 4-bytes at a time. The File size is 63,480,320 bytes. My assumption is that if I loop through this file reading 4 bytes at a time, I should loop 15,870,080 times. The code is: newprogram.cpp =============
3
2823
by: The Cool Giraffe | last post by:
Regarding the following code i have a problem. void read () { fstream file; ios::open_mode opMode = ios::in; file.open ("some.txt", opMode); char *ch = new char; vector <charv; while (!file.eof ()) { do {
0
8444
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8356
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8869
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8781
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8551
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7386
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6198
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5664
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
1775
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.