Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Oct 3, 2000

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 << "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);
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap