I wrote this routine which is supposed to open a fi

Q

I wrote this routine which is supposed to open a file:
myfopen(char *filename, FILE *fp)
{
fp = fopen(filename, "r");
}

But when I call it like this:

FILE *infp;
myfopen("filename.dat", infp);

the infp variable in the caller doesn't get set properly.

✍: Guest

A

Functions in C always receive copies of their arguments, so a function can never ``return'' a value to the caller by assigning to an argument.
For this example, one fix is to change myfopen to return a FILE *:
FILE *myfopen(char *filename)
{
FILE *fp = fopen(filename, "r");
return fp;
}

and call it like this:
FILE *infp;
infp = myfopen("filename.dat");

Alternatively, have myfopen accept a pointer to a FILE * (a pointer-to-pointer-to-FILE):
myfopen(char *filename, FILE **fpp)
{
FILE *fp = fopen(filename, "r");
*fpp = fp;
}

and call it like this:

FILE *infp;
myfopen("filename.dat", &infp);

2015-10-09, 757👍, 0💬