Thread: FILE passing through functions

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    255

    FILE passing through functions

    Hey if memory serves correctly in C++ if i open a file say in main and then want to pass it through a function so i can use it all i have to do is reference it with a little &

    i tried this in C not knowing how to do it in C anyway and it didnt work

    i was curious could someone tell me how i can open a file in main and then pass it through a function?? im guessing youd have to reference it somehow but im not sure?
    hooch

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    The nearest equivalent of a reference in C is a pointer.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    255
    ya cause you do the FILE *filepointerhere

    i tried that but you cant just put in a function parameters a FILE *ffsdfsdfsd is there a way to get around that so i can still use the file in another function besides main?
    hooch

  4. #4
    Registered User wintellect's Avatar
    Join Date
    Mar 2006
    Posts
    24
    something like this:
    Code:
    #include <stdio.h>
    
    int mysub(FILE *ptr);
    
    int main(void)
    {
            FILE *ptr;
    
            if ( (ptr = fopen("test.txt", "w")) == NULL)
                    return(10);
    
            if (fprintf(ptr, "This was printed from main\n") == -1)
                    return(20);
    
            if ( mysub(ptr) == -1)
                    return(30);
    
            return(0);
    }
    
    int mysub(FILE *ptr)
    {
            return( fprintf(ptr, "This was printed from the function mysub\n") );
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fscanf in different functions for the same file
    By bchan90 in forum C Programming
    Replies: 5
    Last Post: 12-03-2008, 09:31 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. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. functions in .C file not recognized in .CPP file
    By tooKool4School6 in forum C++ Programming
    Replies: 1
    Last Post: 06-02-2006, 10:30 AM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM