prev up next   top/contents search

comp.lang.c FAQ list · Question 12.27

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. See question 4.8.

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


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North