Passing FILE pointer to a function

37,899

FILE * needs to be a pointer, so in main openReadFile stays as a pointer. myfunction takes **, so we can update the FILE * with the result from fopen *readFile = fopen... updates the pointer.

int myfunction(char* fileName, FILE** readFile) /* pointer pointer to allow pointer to be changed */
{
    if(( *readFile = fopen(fileName,"r")) == NULL)
    {
        return FILE_ERROR;
    }
    return FILE_NO_ERROR;
}

int main(int argc, char **argv)
{
    FILE* openReadFile; /* This needs to be a pointer. */
    if(myfunction(argv[1], &openReadFile) != FILE_NO_ERROR) /* allow address to be updated */
    {
        printf("\n %s : ERROR opening file. \n", __FUNCTION__);
    }
}
Share:
37,899
Sir DrinksCoffeeALot
Author by

Sir DrinksCoffeeALot

Updated on October 28, 2020

Comments

  • Sir DrinksCoffeeALot
    Sir DrinksCoffeeALot over 3 years

    I'm little bit confused over here, not quite sure about this. What I'm trying to do is to pass the name of a file through terminal/cmd that will be opened and read from.

    myfunction(char* fileName, FILE* readFile)
    {
        if((readFile = fopen(fileName,"r")) == NULL)
        {
            return FILE_ERROR;
        }
        return FILE_NO_ERROR;
    }
    
    int main(int argc, char **argv)
    {
    FILE* openReadFile;
        if(myfunction(argv[1], openReadFile) != FILE_NO_ERROR)
        {
            printf("\n %s : ERROR opening file. \n", __FUNCTION__);
        }
    }
    

    My question is if i pass a pointer openReadFile to myfunction() will a readFile pointer to opened file be saved into openReadFile pointer or do i need to put *readFile when opening.