5

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.

6
  • 3
    You need to pass &openReadFile into the function if you want the updated pointer passed back to the caller. The parameter declaration of the function would be FILE** readFile Commented Oct 27, 2015 at 20:38
  • 2
    ... or pass the successful pointer back as function value, or NULL. Commented Oct 27, 2015 at 20:41
  • Can't i just dereference readFile when fopen-ing? Commented Oct 27, 2015 at 20:41
  • 1
    If you want to read from the file in main() you can't, because it's pointer value is lost after the function returns. Commented Oct 27, 2015 at 20:42
  • Alright, thanks for the answers :) Commented Oct 27, 2015 at 20:43

1 Answer 1

16

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__);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Think i got it, if i would have only one * in int myfunction(char* fileName, FILE** readFile) i would be basicly changing on what readFile is pointing, and with double * im changing on which pointer from main is pointing too. Yay.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.