I'm trying to overload the << and >> operators to serialize a class to
disk. It writes things correctly, but it doesn't read them back correctly.
Can someone tell what I'm doing wrong? Here is an example demonstrating
my problem.
------- tmp.cc --------------
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
class foo {
private:
long keymap[5];
int joymap[5];
int joystick;
bool useJoystick, useDpad;
friend std::ostream &operator<<(std ::ostream &, const foo &);
friend std::istream &operator>>(std ::istream &, foo &);
public:
foo(bool init = true);
};
foo::foo(bool init) {
if (init) {
for (int i = 0; i < 5; i++) {
keymap[i] = static_cast<lon g>(rand() % 1000);
joymap[i] = rand() % 16;
}
joystick = -1;
useJoystick = useDpad = false;
}
}
std::ostream &operator<<(std ::ostream &output, const foo &f) {
for (int i = 0; i < 5; i++) {
output << f.keymap[i];
output << f.joymap[i];
}
output << f.joystick << f.useJoystick << f.useDpad;
return output;
}
std::istream &operator>>(std ::istream &input, foo &f) {
for (int i = 0; i < 5; i++) {
input >> f.keymap[i];
input >> f.joymap[i];
}
input >> f.joystick >> f.useJoystick >> f.useDpad;
return input;
}
int main(int, char **) {
srand(time(NULL ));
foo f, f2(false);
std::fstream out("foo.bar",
std::ios_base:: out | std::ios_base:: binary);
if (!out) {
std::cerr << "fatal: unable to open foo.bar for writing\n";
return -1;
}
out << f;
out.close();
std::cout << "wrote the following to foo.bar...\n" << f << "\n\n";
std::fstream in("foo.bar",
std::ios_base:: in | std::ios_base:: binary);
if (!in) {
std::cerr << "fatal: unable to open foo.bar for reading\n";
return -1;
}
in >> f2;
in.close();
std::cout << "read the following from foo.bar...\n" << f2 << '\n';
return 0;
}
-----------------------------
This is the output I get with mingw/g++ 3.4.2
$ g++ -W -Wall -O2 tmp.cc
$ ./a.exe
wrote the following to foo.bar...
252694219161177 692989-100
read the following from foo.bar...
-120092525792089 878893020092525 744009025399769 623683680200929 192420091454802 55255
$ cat foo.bar
252694219161177 692989-100
The data is being written correctly, I'm just not sure why I can't do
the reverse when I read it from the file.
Thanks,
--John Ratliff 3 1534
John Ratliff wrote: I'm trying to overload the << and >> operators to serialize a class to disk. It writes things correctly, but it doesn't read them back correctly.
Can someone tell what I'm doing wrong? Here is an example demonstrating my problem.
------- tmp.cc -------------- [redacted std::ostream &operator<<(std ::ostream &output, const foo &f) { for (int i = 0; i < 5; i++) { output << f.keymap[i]; output << f.joymap[i]; }
output << f.joystick << f.useJoystick << f.useDpad;
return output; }
std::istream &operator>>(std ::istream &input, foo &f) { for (int i = 0; i < 5; i++) { input >> f.keymap[i]; input >> f.joymap[i]; }
input >> f.joystick >> f.useJoystick >> f.useDpad;
return input; }
[redacted]
You might want to put some spaces in there. Remember, just 'cause you
opened it up in binary mode, doesn't mean the data you put out using
"<<" is. It has to do with newline translations. So when you output
the members of f, it puts them out in ASCII.
That is,
if all member variables of f are 0 (hypothetical), you'll get the
following output:
0000000000000
How is the input parser supposed to know where each field begins?
Try:
std::ostream& operator<<(std: :ostream& os, const foo& f)
{
for (int i = 0; i < 5 ; ++i)
os << f.keymap[i] << " " << f.joymap[i] << " ";
os << f.joystick << " "
<< f.useJoystick << " "
<< f.useDpad << std::endl;
return os;
}
Now, you have the following outputs (again, assuming all 0)
0 0 0 0 0 0 0 0 0 0 0 0 0
So the input parser can determine where each field begins. Note that I
put an 'endl' after the last value.
red floyd wrote: John Ratliff wrote:
I'm trying to overload the << and >> operators to serialize a class to disk. It writes things correctly, but it doesn't read them back correctly.
Can someone tell what I'm doing wrong? Here is an example demonstrating my problem.
------- tmp.cc -------------- [redacted std::ostream &operator<<(std ::ostream &output, const foo &f) { for (int i = 0; i < 5; i++) { output << f.keymap[i]; output << f.joymap[i]; }
output << f.joystick << f.useJoystick << f.useDpad;
return output; }
std::istream &operator>>(std ::istream &input, foo &f) { for (int i = 0; i < 5; i++) { input >> f.keymap[i]; input >> f.joymap[i]; }
input >> f.joystick >> f.useJoystick >> f.useDpad;
return input; }
[redacted]
You might want to put some spaces in there. Remember, just 'cause you opened it up in binary mode, doesn't mean the data you put out using "<<" is. It has to do with newline translations. So when you output the members of f, it puts them out in ASCII.
That is,
if all member variables of f are 0 (hypothetical), you'll get the following output:
0000000000000
How is the input parser supposed to know where each field begins?
Try:
std::ostream& operator<<(std: :ostream& os, const foo& f) { for (int i = 0; i < 5 ; ++i) os << f.keymap[i] << " " << f.joymap[i] << " "; os << f.joystick << " " << f.useJoystick << " " << f.useDpad << std::endl; return os; }
Now, you have the following outputs (again, assuming all 0)
0 0 0 0 0 0 0 0 0 0 0 0 0
So the input parser can determine where each field begins. Note that I put an 'endl' after the last value.
I was thinking along those lines, but I wasn't sure.
Yeah, I know binary mode only means newline translation, but for some
reason I thought it would add terminators or spaces for me. Don't know
why I had that thought.
Thanks,
--John Ratliff
John Ratliff wrote: I'm trying to overload the << and >> operators to serialize a class to disk. It writes things correctly, but it doesn't read them back correctly.
Can someone tell what I'm doing wrong? Here is an example demonstrating my problem.
[snip] The data is being written correctly, I'm just not sure why I can't do the reverse when I read it from the file.
If you look, I bet you'll find that the data in the file is in text
format, not binary. That's because the default stream insertion (<<)
and extraction (>>) operators are for formatted (i.e., text-mode) I/O
only, and I believe they force the file mode to text, no matter what
you opened it as. Use ostream::write( ) and istream::read() in your
operator functions instead of the standard insertion/extraction
operators to read and write in non-text format. You should probably
also check in your operator functions to see if the file is in binary
mode or not.
Alternately, use text mode and separate the values with spaces. This
might yield smaller files if your numbers are generally small: a binary
integer of value 2 would take up four bytes whereas the text version
would take up 2 (one for the text digit, one for the space). Using hex
might also help if the numbers are unsigned.
Cheers! --M This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: BoonHead, The Lost Philosopher |
last post by:
I think the .NET framework is great!
It's nice, clean and logical; in contradiction to the old Microsoft.
It only saddens me that the new Microsoft still doesn't under stand there own rules when it comes to file paths.
A lot of Microsoft installers for example, and also installers of other companies, do not work because they handle paths in the following manner:
|
by: Marc Cromme |
last post by:
I would like to ask a question about (good ?) style and possibilities in
mixing C FILE* and C++ file streams.
The background is that I want to use the C libpng library from within C++,
but I would like to open C++ file streams due to easier exception
handeling and safe closure of file ressources.
Question 1:
I open a standard file stream and want to transfer some binary read bits
|
by: siroregano |
last post by:
Hi Everyone-
I'm new to this group, and almost-as-new to asking programming
questions publicly, so please forgive me if I miss a convention or two!
I have a text file, around 40,000 lines long, where each line is a
string of 4 ASCII characters corresponding to a 12-bit hexadecimal
audio sample. The file reads something like this...
081F
|
by: CGW |
last post by:
I asked the question yesterday, but know better how to ask it, today:
I'm trying to use the File.Copy method to copy a file from a client to
server (.Net web app under IIS ). It looks to me that when I
give a path like @"C:\holdfiles\myfile.txt" it looks on the server C drive.
How do I pull from the client? Do I need a different class and/or method?
Filestream?
--
Thanks,
|
by: petermichaux |
last post by:
Hi,
I'm curious about server load and download time if I use one big
javascript file or break it into several smaller ones. Which is better?
(Please think of this as the first time the scripts are downloaded so
that browser caching is out of the equation.)
Thanks,
Peter
| |
by: sani8888 |
last post by:
Hi
everybody I am a beginner with C++ programming. And I need some help.
How can I start with this program
***********
The program is using a text file of information as
the source of the questions. The program starts by outputting a simple text information
screen:
Question Master
|
by: dbuchanan |
last post by:
Hello,
(Is this the proper newsgroup?)
=== Background ===
I am building a solution with two projects.
One project is my data access layer which contains my DataSet as an xsd
file. The XSD file was built by draging tables from the Data Sources pane.
Auto-generated code created the files associated wtih the XSD file (xss,
|
by: portCo |
last post by:
Hello there,
I am creating a vb application which is some like like a questionare.
Application read a text file which contains many questions and display
one question and the input is needed from user to calculate the score.
Here is a problem.
I can read a text file. However, it's read whole file at a time. So,
|
by: saytri |
last post by:
Hi guys!
I am making a quiz. The questions are stored in a binary file. I made an option in the quiz where a user can add a question to the binary file. Altough this works, the problem is that whenever a user enters a new question is just overwrites the whole file, instead of adding it to the rest of the questions in the binary file. Do i have something wrong? Thanks a lot. :-)
This is the piece of code that adds a question to binary file:...
|
by: =?Utf-8?B?R2lkaQ==?= |
last post by:
Hi,
In my windows applicationm, i need to excute a batch file.
this batch file throws some text and questions to the screen, i need to
catch the standard Output, check if it's a question, in case it's a question,
i want to popup a messageBox or something, and bring back to the batch file
the result (Yes\No question). I know how to excute the batch file and get all
the Standard output at the end, but i don't know who can i read it line by...
|
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...
| |
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,...
|
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...
|
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,...
|
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...
|
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();...
|
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |