Why FILE * does not store the address of an open file

#include <stdio.h>

FILE * Openfile(char *filename,char *mode, FILE *fp);

int main(){

    FILE *fp=NULL;
    char *filename = "simple_index.file";
    char *openmode = "w";

    printf("FP(before call function):%p\n", fp);
    FILE *newfp = Openfile(filename, openmode, fp);
    printf("FP(after call function): %p\nNEWFP: %p\n", fp, newfp);                  

    return 0;
}

FILE * Openfile(char *filename,char *mode, FILE *fp){
    printf((fp = fopen(filename, mode)) ? "Good opening %s file\n": "Error open %s file\n", filename);          
    return fp;

}

Result:

FP(before call function):0x0
Good opening simple_index.file file
FP(after call function): 0x0
NEWFP: 0x800bc7140

A pointer to the file structure does not store the address of an open file after using a function to open a file in the call Openfile() function.

Why does FP not save the state after use in function? Why need back for save?


Solution 1:

This happens because C uses pass-by-value for function argument passing.

If you want to make changes to a variable passed as an argument to a function from that function itself, you'll be needing a pointer to that variable to be passed to the function and inside the function, you can modify the value pointed by the pointer and in the caller, it will persist.

Otherwise, to get the value back from the called function, usually we return the value and assign it to the variable in the caller function.

Solution 2:

fopen stores the updated pointer but to access that you need to provide the address of the pointer.

Try with:

FILE *newfp = Openfile(filename, openmode, &fp);

FILE * Openfile(char *filename,char *mode, FILE **fp){
    printf((*fp = fopen(filename, mode)) ? "Good opening %s file\n": "Error open %s file\n", filename);          
    return *fp;

}

Now *fpand newfp will print the same value