Leon Breedt wrote:
> int fopenfile(FILE *fp, char *fname)
> {
> fp = fopen(fname, "r+");
> if (!fp)
> fp = fopen(fname, "w+"); /* create if not found */
>
> return 0;
> }
This don't work because 'fp' is passed by value :
when you do
fopenfile( file, filename);
the value of 'file' is copied to the stack and fopenfile will use this
copy.
As a consequence fopenfile will modifie the copied value of 'file'
but not the content of the pointer 'file'. So after the call to
fopenfile,
the 'file' pointer will be unchanged.
To make this thing work, you need to pass the parameter 'fp' by
reference ( ie pass the adress of 'file' so that fopenfile can
modifie its contents).
int fopenfile( FILE **fp, char *fname) {
*fp = fopen( fname, "r+");
if ( !*fp)
*fp = fopen( fname, "w+");
return *fp != NULL;
}
an easier solution would be to use :
FILE *
fopenfile( char *filename) {
FILE *fp;
fp = fopen( filename, "r+");
if ( !fp)
fp = fopen( filename, "w+");
return fp;
}
I hope this help a bit.
david