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:
fstream * of;
};
void open(ofstruct & fs)
{
std:
fstream ofile("of.txt",std::ios:
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;
}
------------------------------------------------------------------------------------------
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:
};
void open(ofstruct & fs)
{
std:
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;
}
------------------------------------------------------------------------------------------