Writing to File from Several Functions.

Writing to File from Several Functions.

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

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

See also  How HealthStream Learning Center Supports Healthcare Education and Compliance

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist