473,545 Members | 1,995 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Loading/Saving a structure using <fstream>

Hi,

I have always used fopen and FILE* to load and save structures to file.
I am trying to convert all the older code to use proper C++ calls...
the following code works properly but I would like to know if I am
using the fstream methods properly. (as long as I am cleaning up I
might as well do it right). By the way, this is just a bogus example
with a structure, values and filename for demonstration purposes.

PS-> I have a funny feeling casting my structure to a char* is the
wrong approach! :)

#include <iostream>
#include <fstream>

struct stAnything
{
int nInteger;
long lLong;
char cChar;
double dDouble;
};

int main(void)
{
std::string sFilename = "C:/test.bin";
stAnything stSomeStructure ;

stSomeStructure .nInteger = 5; // bogus values
stSomeStructure .lLong = 10;
stSomeStructure .cChar = 'A';
stSomeStructure .dDouble = 5.1;

// Save the structure to a binary file
std::ofstream outFile;
outFile.open(sF ilename.c_str() , std::ofstream:: out |
std::ofstream:: binary);
if (!outFile.is_op en())
{
std::cout << "Could not open the file for output." << std::endl;
return 1;
}
outFile.write(( const char *) &stSomeStructur e, sizeof(stAnythi ng));
outFile.close() ;

// Clear the structure
stSomeStructure .nInteger = 0;
stSomeStructure .lLong = 0;
stSomeStructure .cChar = ' ';
stSomeStructure .dDouble = 0.0;

// Load the structure from a binary file
std::ifstream inFile;
inFile.open(sFi lename.c_str(), std::ofstream:: in |
std::ofstream:: binary);
if (!inFile.is_ope n())
{
std::cout << "Could not open the file for input." << std::endl;
return 1;
}
inFile.read((ch ar *) &stSomeStructur e, sizeof(stAnythi ng));
inFile.close();

// Show the loaded contents
std::cout << "{" << stSomeStructure .nInteger << ", " <<
stSomeStructure .lLong << ", " <<
stSomeStructure .cChar << ", " <<
stSomeStructure .dDouble << "} " << std::endl;
return 0;
}

Dec 1 '05 #1
4 7842
On 2005-12-01, ad***********@g mail.com <ad***********@ gmail.com> wrote:
I have always used fopen and FILE* to load and save structures
to file.
The approach has the same drawbacks in C++ as it did in C. It's
not portable. It won't work at all for structs that aren't Plain
Old Data types.
I am trying to convert all the older code to use proper C++
calls...
I'm not sure it's really an improvement over the original C.

You may want to read about serialization. Reading and writing
your structs as plain old text won't be as compact, but it's
quite portable, and gives clients the benefit of human-readable
data files.
the following code works properly but I would like to know if I
am using the fstream methods properly. (as long as I am
cleaning up I might as well do it right). By the way, this is
just a bogus example with a structure, values and filename for
demonstration purposes.

PS-> I have a funny feeling casting my structure to a char* is
the wrong approach! :)
It's normally a bad idea. In this case, it's doesn't make your
code any less portable. But prefer C++ style casts intead of the
C-style cast used.
outFile.write(( const char *) &stSomeStructur e, sizeof(stAnythi ng));


outFile.write(r einterpret_cast <const char *>(&stSomeStruc ture)
, sizeof(stAnythi ng));

--
Neil Cerutti
Dec 1 '05 #2
ad***********@g mail.com wrote:
Hi,

I have always used fopen and FILE* to load and save structures to file.
I am trying to convert all the older code to use proper C++ calls...
the following code works properly but I would like to know if I am
using the fstream methods properly. (as long as I am cleaning up I
might as well do it right). By the way, this is just a bogus example
with a structure, values and filename for demonstration purposes.
See the FAQ for more robust techniques that will work with all classes
and structs not just ones without virtual functions or, e.g.,
std::vectors:

http://www.parashift.com/c++-faq-lit...alization.html

And check out Boost's serialization library:

http://boost.org/libs/serialization/doc/index.html
PS-> I have a funny feeling casting my structure to a char* is the
wrong approach! :)
For binary mode, you'll have to do that cast eventually.
#include <iostream>
#include <fstream>

struct stAnything
{
int nInteger;
long lLong;
char cChar;
double dDouble;
};

int main(void)
Using void like that is an "abominatio n"
(http://www.research.att.com/~bs/sibling_rivalry.pdf).
{
std::string sFilename = "C:/test.bin";
Should be const.
stAnything stSomeStructure ;

stSomeStructure .nInteger = 5; // bogus values
stSomeStructure .lLong = 10;
stSomeStructure .cChar = 'A';
stSomeStructure .dDouble = 5.1;

// Save the structure to a binary file
std::ofstream outFile;
outFile.open(sF ilename.c_str() , std::ofstream:: out |
std::ofstream:: binary);
Prefer to open and close with the constructor and destructor,
respectively, unless you need to do differently. (In this test program,
you would actually need to close the output file manually or else move
the serialization to a separate function so the file is closed via the
destructor when the function returns.)
if (!outFile.is_op en())
Better would be:

if( !outFile )
{
std::cout << "Could not open the file for output." << std::endl;
return 1;
}
outFile.write(( const char *) &stSomeStructur e, sizeof(stAnythi ng));
You didn't check that the write succeeded, and you should use C++-style
casts - reinterpret_cas t would be appropriate here to signal a
potentially shady conversion.

Similar comments apply to the read portion.
outFile.close() ;

// Clear the structure
stSomeStructure .nInteger = 0;
stSomeStructure .lLong = 0;
stSomeStructure .cChar = ' ';
stSomeStructure .dDouble = 0.0;

// Load the structure from a binary file
std::ifstream inFile;
inFile.open(sFi lename.c_str(), std::ofstream:: in |
std::ofstream:: binary);
if (!inFile.is_ope n())
{
std::cout << "Could not open the file for input." << std::endl;
return 1;
}
inFile.read((ch ar *) &stSomeStructur e, sizeof(stAnythi ng));
inFile.close();

// Show the loaded contents
std::cout << "{" << stSomeStructure .nInteger << ", " <<
stSomeStructure .lLong << ", " <<
stSomeStructure .cChar << ", " <<
stSomeStructure .dDouble << "} " << std::endl;
return 0;
}


You might also be interested in this section of the FAQ:

http://www.parashift.com/c++-faq-lite/input-output.html

Cheers! --M

Dec 1 '05 #3
mlimber <ml*****@gmail. com> wrote:
ad***********@g mail.com wrote:
// Save the structure to a binary file
std::ofstream outFile;
outFile.open(sF ilename.c_str() , std::ofstream:: out |
std::ofstream:: binary);


Prefer to open and close with the constructor and destructor,
respectively, unless you need to do differently. (In this test program,
you would actually need to close the output file manually or else move
the serialization to a separate function so the file is closed via the
destructor when the function returns.)


Alternately, he could wrap the code that uses outFile in an extra set of
{ }'s to limit its scope:

// ...
stSomeStructure .dDouble = 5.1;

{
// Save the structure to a binary file
std::ofstream outFile(sFilena me.c_str(),
std::ofstream:: out | std::ofstream:: binary);
if (!outFile)
{
std::cout << "Could not open the file for output." << std::endl;
return 1;
}
outFile.write(( const char *) &stSomeStructur e, sizeof(stAnythi ng));
}

// rest of code
--
SLuGHEAd78 | "Today, if you are not confused, you are
A.K.A. DJ Slant Eye, Chudmuffin, | just not thinking clearly."
Marcus Kwok, Silly Chink, Nuprin | -U. Peter
Dec 1 '05 #4
Thanks for all the suggestions... they seem to do the trick.

Dec 1 '05 #5

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

Similar topics

6
3190
by: Armando | last post by:
Hallo ! I habe some error in my programm,because i use <fstream.h>,I want to use <fstream> but i don´t know which fonctions i must modify in my program ? Thanks you for your help. Armando.
11
5370
by: Charles L | last post by:
I have read that the inclusion of <fstream.h> makes the inclusion of <iostream.h> unnecessary. Is this correct? Charles L
1
2125
by: Macca | last post by:
Hi, I have been using <fstream.h> in stdafx.h,(i'm using MFC) to output to text files. I have now started to use vectors and when i added #include <vector> using namespace std; to stdafx.h, I found that to compile i had to change <fstream.h> to <fstream> to get it to compile.
4
4829
by: nils | last post by:
Hi all, Recently I started migrating a gcc project to Visual Studio C++ (dotnet). The problem is that I cannot include any iostream header-file: #include <fstream> int main (int argc, char * argv) { printf("hello world"); return 0;
4
6966
by: Falos425 | last post by:
Okay, I've got a driver.cpp, a section.cpp, and a section.h because I've got a 'section' class. I have an #include <fstream> in the section.h and then section.cpp has an #include "section.h" Trouble is, one of the class functions is supposed to (homework) take a string as a parameter, and use it as the filename. So in the function, I've...
31
560
by: grubbymaster | last post by:
hello i'm extracting from a file numbers that are stored on each line. this is the only way i know to extract each line at a time from a file , using <fstream> <ostream> : char buffer; ifstream LZW(sz_path);
5
4155
by: neowillis | last post by:
code: #include <iostream> #include <fstream> #include <string> using namespace std; int main() {
0
7484
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...
0
7415
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...
0
7928
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...
0
7775
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5997
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...
0
4963
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...
0
3470
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3451
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1902
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.