devxlogo

Writing to File from Several Functions.

Writing to File from Several Functions.

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 

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 

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);}

devx-admin

Share the Post: