Question:
The code below creates a file, Basket.doc, in the current directory.
I am using a compiler with a component I would like to place in fWrite() to let me vary the entire path and file name (i.e. outName). The trouble is I want outSide to be valid from fFinish(), too.Do I need a global variable or a pointer of some kind?
char outName[] = "Basket.doc";ofstream outSide(outName);void fWrite() { outSide << "This is a test." << endl;}void fFinish(){ outSide.close();}int main(){ fWrite(); fFinish();}
Answer:
You certainly don't need a global variable here. Simply pass a reference to ofstream to your functions and have them access that reference:
void fWrite(ofstream & outSide) { outSide << "This is a test." << endl;}void fFinish(ofstream & outSide){ outSide.close();}
You will need to change main() as well: create the outSide object inside main(), and pass it the the invoked functions, as follows:
int main(){ outName[] = "Basket.doc"; ofstream outSide(outName); fWrite(outSide); fFinish(outSide);}