473,465 Members | 1,458 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Writing Struct to File doesn't work - what am I doing wrong?

This code doesn't work - the first retrieval of t2 returns valid data,
the subsequent do not. Please help!!!

int main(int argc, char* argc){
struct Test{
int i;
int j;
intk;
int l;
}

Test Test1;
Test1.i = 99;
Test1.j = 777;
Test1.k = 12345;
Test1.l = 876;

fstream fout;
fout.open("test.txt", ios::out);

for (int i=0; i<10; i++)
fout.write(reinterpret_cast<char*>(&Test1), sizeof(Test));
fout.close();

fstream fin;
fin.open(test.txt", ios::in);
for(int i=0; i<10; i++){
char c[sizeof(Test)];
fin.get(c, sizeof(Test));
Test t2;

// === THIS COPY OF t2 CONTAINS CORRECT DATA FIRST TIME BUT NOT
SUBSEQUENT
// TIMES!!!!!!!!!
memcpy(&t2, c, sizeof(Test));

}


}

Nov 5 '06 #1
6 1704
pa***********@jhuapl.edu wrote:
This code doesn't work - the first retrieval of t2 returns valid data,
the subsequent do not. Please help!!!
#include <fstream>
int main(int argc, char* argc){
struct Test{
int i;
int j;
intk;
int l;
}
missing trailing semi-colon above.
>
Test Test1;
Test1.i = 99;
Test1.j = 777;
Test1.k = 12345;
Test1.l = 876;

fstream fout;
fout.open("test.txt", ios::out);
// you must be using MS Windows... to read/write binary
// data you have to open the file in binary mode.
fout.open("text.txt", ios_base::out | ios_base::binary );
>
for (int i=0; i<10; i++)
fout.write(reinterpret_cast<char*>(&Test1), sizeof(Test));
fout.close();

fstream fin;
fin.open(test.txt", ios::in);
fin.open("test.txt", ios_base::in | ios_base::binary );

for (int x = 0; x < i; ++x )
{
Test t2;
fin.read(reinterpret_cast<char*>(&t2), sizeof(Test));
}
for(int i=0; i<10; i++){
char c[sizeof(Test)];
fin.get(c, sizeof(Test));
Test t2;

// === THIS COPY OF t2 CONTAINS CORRECT DATA FIRST TIME BUT NOT
SUBSEQUENT
// TIMES!!!!!!!!!
memcpy(&t2, c, sizeof(Test));

}


}
Nov 5 '06 #2

pa***********@jhuapl.edu wrote:
This code doesn't work - the first retrieval of t2 returns valid data,
the subsequent do not. Please help!!!
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
#include <iterator>

struct Test {
int i, j, k, l;
};
>
int main(int argc, char* argc){struct Test {
int i, j, k, l;
};
struct Test{
int i;
int j;
intk;
int l;
}
Types need a semicolon and are not placed in main()
>
Test Test1;
Test1.i = 99;
Test1.j = 777;
Test1.k = 12345;
Test1.l = 876;
Either an aggregate list or Test ctor would be handy.

Test test = {99, 777, 12345, 876};
>
fstream fout;
fout.open("test.txt", ios::out);
if(!fout || !fout.is_open() )
{
std::cout << "error while opening file for output.\n";
return -1;
}
>
for (int i=0; i<10; i++)
fout.write(reinterpret_cast<char*>(&Test1), sizeof(Test));
fout.close();
If you wrote a global operator<< to stream Test data you'ld benefit
since operators can be reused for both writing to file and writing to
std::cout.

for (int i = 0; i < 10; ++i)
{
ofs << test; // depends on global op<<
}
>
fstream fin;
fin.open(test.txt", ios::in);
for(int i=0; i<10; i++){
char c[sizeof(Test)];
fin.get(c, sizeof(Test));
Test t2;
Don't use char, use std::string instead.

// input file stream
std::ifstream ifs;
ifs.open("test.txt"); // its set to std::ios::in already
if(!ifs || !ifs.is_open() )
{
std::cout << "error while opening file for input.\n";
return -1;
}

// load a vector with Test data
std::vector< Test vtest; // container
std::string buffer; // buffers each line
std::istringstream iss; // used to dissect data from buffer
while(std::getline(ifs, buffer, '\n'))
{
Test temp;
iss.str(buffer);
iss >temp.i >temp.j >temp.k >temp.l;
iss.clear();
vtest.push_back(temp); // push temp onto container
}
if(!ifs.eof()) // if std::getline did *not* fail because of eof...
{
std::cout << "error while reading file.\n";
std::cout << "end of file not found.\n";
return -1;
}
// print vector using copy algorithm
std::copy( vtest.begin(),
vtest.end(),
std::ostream_iterator<Test >( std::cout ));
return 0;
}

I leave the global operator<< to you as an exercise.
Have fun.

Nov 5 '06 #3
pa***********@jhuapl.edu wrote:
fout.write(reinterpret_cast<char*>(&Test1), sizeof(Test));
fin.get(c, sizeof(Test));
Instead of get, use read. get reads text. write and read deal in binary
data. And, as Larry suggested, open the file in both cases in binary mode.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Nov 5 '06 #4
On 5 Nov 2006 00:19:07 -0800 in comp.lang.c++, "Salt_Peter"
<pj*****@yahoo.comwrote,
>Types need a semicolon and are not placed in main()
Nothing wrong with declaring a type in main() if that is exclusively
where you are going to use it.
>Either an aggregate list or Test ctor would be handy.

Test test = {99, 777, 12345, 876};
Aggregate initialization, yes. Constructor, no; it needs to be a POD
struct if he is going to binary read and write it.
>If you wrote a global operator<< to stream Test data you'ld benefit
since operators can be reused for both writing to file and writing to
std::cout.
But not appropriate for the binary writing purpose.
>Don't use char, use std::string instead.
His array of char is not being used as a string. But better to declare
a Test instance and read directly into that.

The main points are still: open with ios::binary flag and then use
read() and write().

Nov 5 '06 #5

David Harmon wrote:
On 5 Nov 2006 00:19:07 -0800 in comp.lang.c++, "Salt_Peter"
<pj*****@yahoo.comwrote,
Types need a semicolon and are not placed in main()

Nothing wrong with declaring a type in main() if that is exclusively
where you are going to use it.
ok, good to know
>
Either an aggregate list or Test ctor would be handy.

Test test = {99, 777, 12345, 876};

Aggregate initialization, yes. Constructor, no; it needs to be a POD
struct if he is going to binary read and write it.
yep, makes sense
>
If you wrote a global operator<< to stream Test data you'ld benefit
since operators can be reused for both writing to file and writing to
std::cout.

But not appropriate for the binary writing purpose.
Don't use char, use std::string instead.

His array of char is not being used as a string.
i realize that, its not a string, its a pseudo-byte array.
But better to declare
a Test instance and read directly into that.
Thats what i want to hear, no need for the reinterpret_cast.
>
The main points are still: open with ios::binary flag and then use
read() and write().
Yes, it makes perfect sense and a better alternative, thank-you.

Nov 5 '06 #6
THANK YOU!!! I did not realize that "read()" should be used for binary
data. Once I switched to that everything worked like a charm.

Nov 7 '06 #7

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

Similar topics

4
by: Nhwk | last post by:
I have an unsigned char banner, which contains data for a 12x8 bitmap file. I am attempting to construct and write to disk a .bmp file with this data. So far, I started by constructing the...
6
by: Sebastian Kemi | last post by:
How should a write a class to a file? Would this example work: object *myobject = 0; tfile.write(reinterpret_cast<char *>(myobject), sizeof(*object)); / sebek
7
by: Keith Dewell | last post by:
Greetings! My current job has brought me back to working in C++ which I haven't used since school days. The solution to my problem may be trivial but I have struggled with it for the last two...
3
by: Emanuele Blanco | last post by:
Hi there, I just compiled a program that uses linked lists (needed it as an homework for my Programming course at University). It works flawlessly, even if I notice a thing. Here's my linked...
6
by: hpy_awad | last post by:
I am writing stings ((*cust).name),((*cust).address)to a file using fgets but rabish is being wrote to that file ? Look to my source please and help me finding the reason why this rabish is being...
0
by: bohuge | last post by:
Hey! At the time being I'm working on a backup solution for a Qtek9090 pocketpc, which should be able to find and backup outlook data to a server, local files, messages and contact from the sim...
0
by: georges the man | last post by:
The purpose: • Sorting and Searching • Numerical Analysis Design Specification You are to write a program called “StockAnalyser”. Your program will read a text file that contains historical...
19
by: rmr531 | last post by:
First of all I am very new to c++ so please bear with me. I am trying to create a program that keeps an inventory of items. I am trying to use a struct to store a product name, purchase price,...
8
by: zaheer031 | last post by:
I am using the following code typedef struct A { int x; int y; int z; }; int main(void) {
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
1
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...
0
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...
0
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,...
0
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...
0
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...
0
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 ...

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.