writes to files passed as struct of ofstream objects fail

M

m vaughn

I wanted to hold information about open files in a struct and be able
pass it around, but the behavior is not what I would expect. Can
someone tell me why this doesn't work? (Even better, what is the
proper way to do this, eg, without the pointers and such). As is
probably obvious, I am not terribly knowledgable here.

The *fs.of<< ... statement in main() does nothing in gcc 3.2.2 and
gives a seg fault in gcc 3.2 (Mandrake linux 9.1 and 9.0).

thanks

m

---------------------------------------------------------------------------------------------
// -*- c++ -*-
//writes to file passed as struct of ofstream object fails
#include <iostream>
#include <fstream>

struct ofstruct{
std::eek:fstream * of;
};

void open(ofstruct & fs)
{
std::eek:fstream ofile("of.txt",std::ios::eek:ut);

if( ofile.fail()){
std::cerr<<"of.txt : file could not be opened";
exit(1);
}
fs.of = &ofile;
std::cout<<*fs.of<<" "<<fs.of<<" is the fobj in open"
<<std::endl; // gives addresses
ofile<<"some filler"
<<std::endl; // writes to file, of course
*fs.of<<"some more filler"
<<std::endl; // writes to file as well
}


int main()
{
ofstruct fs;

open(fs);
std::cout<<*fs.of<<" "<<fs.of<< " is the fobj in main"
<<std::endl; // same addresses
*fs.of<< "filler from main"
<< std::endl; // but doesn't write to file

return 0;
}

------------------------------------------------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top