Thread: fin fout, file pointer question

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    84

    fin fout, file pointer question

    Hello

    I wrote a program that has a function in it that prints to an output file...

    I want to use the file pointer fout

    But whenever I declare fout outside of the main function... like a global variable, I get an error

    and if I declare fout in main, then my function can't see it

    does anyone now a way out of this problem?

  2. #2
    Registered User
    Join Date
    Sep 2005
    Posts
    84
    this is what I have in main:

    Code:
                     FILE *fin,*fout;
                     fin = fopen("cp20550.dat", "r");
                     fout = fopen("cp20550.out", "w");

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You can declare them outside of a function. You can't call fopen outside of a function. So move the two function calls inside a function of your choice.


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    There is nothing wrong with declaring the FILE pointers outside of a function:
    Code:
    FILE *fin, *fout;
    
    void foo(void)
    {
        fin = fopen(...);
        fout = fopen(...);
    }
    
    int main(void)
    {
        foo();
        /* you can use fin/fout here too */
        return 0;
    }

  5. #5
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You can also declare the FILE pointers inside main() and then pass them to your function. You'll just need to pass pointers to the FILE pointers if you want main() to see the changes:
    Code:
    #include <stdio.h>
    
    void open_files(FILE **fin, FILE **fout)
    {
      *fin = fopen("cp20550.dat", "r");
      *fout = fopen("cp20550.out", "w");
    }
    
    int main(void)
    {
      FILE *fin, *fout;
    
      open_files(&fin, &fout);
    
      fclose(fin);
      fclose(fout);
    
      return 0;
    }
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM