I want to open, in a function, a file to be used within the scope of main for example. Nevertheless, the pointer is being set to nil in the code 1. So far I have solve the problem using code 2.
Nevertheless, I do not understand very well why 2 solves the problem. If someone could clarify me that I would appreciate it.
As @melpomene pointed out the question is solved in Why is FILE * stream sent to null when stream is assigned to fopen inside a function?, thanks to the fact that some memory should be allocated for FILE *; and so it must be pass by reference. In spite of that I consider that the question is subtly different because I haven't reflect that the same process (dynamic allocation) was done by fopen to the the pointer FILE * stream it is assigned.
Example 1:
#include <stdio.h>
#include <stdlib.h>
int ReadFileName(char * filename, char * readmode, FILE *stream);
int main(){
FILE * stream;
ReadFileName("gaussian10.dat","rb", stream);
printf("%p\n",stream);
return 0;
}
int ReadFileName(char * filename, char * readmode, FILE * stream){
stream = fopen(filename,readmode);
printf("%p\n",stream);
if (stream == NULL){
printf("It was not possible to read %s\n",filename);
exit(-1);
}
return 0;
}
Example 2:
#include <stdio.h>
#include <stdlib.h>
int ReadFileName(char * filename, char * readmode, FILE **stream);
int main(){
FILE * stream;
ReadFileName("gaussian10.dat","rb", &stream);
printf("%p\n",stream);
return 0;
}
int ReadFileName(char * filename, char * readmode, FILE **stream){
*stream = fopen(filename,readmode);
printf("%p\n",*stream);
if (*stream == NULL){
printf("It was not possible to read %s\n",filename);
exit(-1);
}
return 0;
}