I'm having problems passing a file pointer through nested functions.
In the code below, main calls func1 which calls func1a which calls openFile. With some modification to the code (to flush and close the file) openFile can write to the file it has opened.
If func1a is called with the file pointer initialised to NULL, the file pointer is not null before returning from the function. func1a can't write to the file, presumably because the pointer is pointing at something other than the file, but calling fprintf with the file pointer doesn't generate a segmentation fault.
Testing the file pointer in func1 returns NULL. Obviously because of this attempting to write to the file later in the program causes a segmentation fault.
I know the problem has to do with the way I'm passing the file pointer and/or the struct which contains it between functions. I can be fairly certain of this because originally, openFile took a file pointer as a parameter rather than returning it, and testing the file pointer in func1a returned NULL.
I've read several forum posts and tutorials that say that, because a file pointer is already a pointer, it should be passed as-is rather than passing a pointer to it. This doesn't seem to work for me, and I've spent the last few weeks messing around with pointers and pointers to pointers, still with the same results.
When compiling the code using lcc under Windows XP, I get the warning
Warning d:\testpointers.c: 39 Missing prototype for 'openFile'
which refers to the line myFile = openFile();
Thanks in advance for any help you can give me.
FILE *file = fopen("D:\\test1.txt","w");
if(file == NULL)
printf("openFile: file is null\n");
int func1a(FILE *myFile)
myFile = openFile();
if(myFile == NULL)
printf("func1a: file is null\n");
int func1(myStruct *a)
int status = func1a(a->myFile);
if(a->myFile == NULL)
printf("func1: file is null\n");
a.myFile = NULL;
int status = 0;
status = func1(&a);