Newbie Question: Passing a File

This is a discussion on Newbie Question: Passing a File within the C++ Programming forums, part of the General Programming Boards category; Hello... I was wondering if anyone could tell me how to open a file in one function and write data ...

  1. #1
    Unregistered
    Guest

    Newbie Question: Passing a File

    Hello... I was wondering if anyone could tell me how to open a file in one function and write data to the file in another? Or is that considered bad programming?

    My code is below. It has errors.

    Code:
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <cstring>
    
    void File1();
    void File2( ofstream );
    
    int main()
    {
    
    
       File1();
       system("PAUSE");
       exit(0);
    
    }
    
    void File1()
    {
    
       char FILE[65];    
       strcpy(FILE, "testfile");
       strcat(FILE, ".txt");
       ofstream fout(FILE, ios::out|ios::app);
    
       fout << "File1" << endl;
    
       File2(fout);
    
       fout.close();
    
    
    }
    
    void File2( ofstream fout )
    {
    
       fout << "File2" << endl;
    
    
    }

  2. #2
    Registered User
    Join Date
    Dec 2001
    Posts
    421
    No, there's nothing wrong with doing that at all.

    void File2( ofstream );

    This isn't the prototype you need though. I should be:

    void File2( ofstream& );
    and
    void File2( ofstream& fout )

    that should work ok (BTW, i haven't compiled and/or tested your code at all... it's just a suggestion!).

    good luck!
    U.
    Quidquid latine dictum sit, altum sonatur.
    Whatever is said in Latin sounds profound.

  3. #3
    Unregistered
    Guest
    Thanks. That fixed it.

  4. #4
    Registered User Liam Battle's Avatar
    Join Date
    Jan 2002
    Posts
    114
    nope not bad, i do that myself, a function should be small and concise...

    just make sure you pass by reference all the time.. you dont want to keep passing by value and wasting resource time
    LB0: * Life once school is done
    LB1: N <- WakeUp;
    LB2: N <- C++_Code;
    LB3: N >= Tired : N <- Sleep;
    LB4: JMP*-3;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  3. File input question from a newbie
    By Dylancougar in forum C Programming
    Replies: 9
    Last Post: 10-20-2005, 06:14 PM
  4. Replies: 3
    Last Post: 03-04-2005, 01:46 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21