if you send a file pointer to a function to be opened, you need to use FILE ** in the function parameters and reference the pointer as myfile*. why the double pointer?
if you send a file pointer to a function to be opened, you need to use FILE ** in the function parameters and reference the pointer as myfile*. why the double pointer?
if you do not pass the pointer by address, you are passing it by value, which means a copy of the pointer is placed on the stack. If you try to allocate memory or open files from within the function scope, the pointer(copy) is lost when the function goes out of scope, and you have no way of finding the file or memory...
You don't have to pass the pointer in by address, but you will have to return a copy of the FILE* from the function.
It all depends on how the function is coded :Originally posted by [EMOBA]
You don't have to pass the pointer in by address, but you will have to return a copy of the FILE* from the function.
Here's how both would be used :Code:void OpenStream( FILE** fp, char* mode, char* fileName ) { .. .. } //Or the second way FILE* OpenStream( char* mode, char* fileName ) { .. .. }
Code://For the first method FILE *fp1; OpenStream(&fp1,"r","blah"); //For the second method FILE *fp1; fp1 = OpenStream("r","blah");
when i'm passing the file pointer to the function that will open the file, i do the following:
i'm not returning the file to the calling function, just the return status. i haven't gotten into memory allocation with regards to opening files, so it appears that i need to do some research in that area. thanks for the replies.Code:long openTransactionFile( FILE **pfFile ) { long lRetCode = SUCCESS; /* open the file for reading */ *pfFile = fopen( TRANSACTION_FILE_NAME, "r" ); if ( *pfFile == NULL ) { printf( "openTransactionFile: %s file does not exist \n"); lRetCode = FAILURE; } /* return status */ return(lRetCode); }
Your code looks fine. I just test it and was right. Could you further explain what is confusing you?
she/he was wondering why it was necessary to pass a pointer to a pointer into the function, instead of just passing the pointer...
Don't use double indirection here. Not necessary. Not correct. As you've shown, it confuses you and that's because it's not warranted in this instance.
Reprototype with just FILE* -- the address of your file pointer.
It is not the spoon that bends, it is you who bends around the spoon.
Actually for what you are doing you do need a pointer to a FILE pointer. Here is why:
FILE *file: is a 32-bit number that is the address of a file.
&file: would mean the address of that pointer.
In order for a function to set the actual value of a pointer (not the data it is pointed to) you need to have a pointer to it. So once again, your function is 100% correct. Keep up the good work.