0

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;
}
  • `f(x)` can't modify `x`. – melpomene Jul 21 '19 at 16:56
  • I propose you add some more of these nice debug-printf to closely inspect the values of `stream` in `main()` and inside the two variations of the `ReadFileName()` function, to become enlightened. – alk Jul 21 '19 at 16:57
  • Also please note: ["*We can solve any problem by introducing an extra level of indirection.*"](https://en.wikipedia.org/wiki/Fundamental_theorem_of_software_engineering) ;) – alk Jul 21 '19 at 17:00
  • Example 1 uses `FILE *stream` while Example 2 uses `FILE **stream`. Try drawing a picture of how the pointers work - it turns out that example 1 can't change what `stream` points to but example 2 can. – Kevin W Matthews Jul 21 '19 at 17:03

0 Answers0