Interview Questions

I wrote this routine which is supposed to open a fil

C Interview Questions and Answers


(Continued from previous question...)

I wrote this routine which is supposed to open a fil

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.

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);

(Continued on next question...)

Other Interview Questions