nergal wrote:
Hi,
I've been staring myself blind on the same little code now and I cant
see the problem. The filepointer seems to not change when I open it in
a function.
I've written like this (a bit pseudo here):
void func(FILE* file)
{
/* print addr of file (2)*/
file = fopen("thefile", "wb"); /* open as binary */
/* print addr of file (3)*/
}
void callingFunc(void)
{
FILE* fileptr;
/* print addr of fileptr (1)*/
func(fileptr);
/* print addr of fileptr again (4) */
}
#include <stdio.h>
#define FNAME "thefile"
void openfile(FILE ** file)
{
printf("%s.%d: *file = %p\n", __func__, __LINE__, (void *) *file);
*file = fopen(FNAME, "wb"); /* open as binary */
printf("%s.%d: *file = %p\n", __func__, __LINE__, (void *) *file);
}
void closeandremove(FILE ** file)
{
printf("%s.%d: *file = %p\n", __func__, __LINE__, (void *) *file);
printf("fclose returned %d\n", fclose(*file));
printf("remove returned %d\n", remove(FNAME));
printf("%s.%d: *file = %p\n", __func__, __LINE__, (void *) *file);
*file = 0;
printf("%s.%d: *file = %p\n", __func__, __LINE__, (void *) *file);
}
int main(void)
{
FILE *fileptr = 0;
printf("[output]\n");
printf("%s.%d: fileptr = %p\n", __func__, __LINE__,
(void *) fileptr);
openfile(&fileptr);
printf("%s.%d: fileptr = %p\n", __func__, __LINE__,
(void *) fileptr);
if (fileptr) {
closeandremove(&fileptr);
printf("%s.%d: fileptr = %p\n", __func__, __LINE__,
(void *) fileptr);
}
else
printf("openfile() failed\n");
return 0;
}
[output]
main.26: fileptr = 0
openfile.7: *file = 0
openfile.9: *file = 20d98
main.29: fileptr = 20d98
closeandremove.14: *file = 20d98
fclose returned 0
remove returned 0
closeandremove.17: *file = 20d98
closeandremove.19: *file = 0
main.33: fileptr = 0
>
(1) Fileptr address becomes XXX
(2) File addr becomes XXX
(3) File addr becomes YYY
(4) File addr becomes XXX
The correct address of the file pointer must be YYY since its in that
function I open it. But why doesn't it change in the calling function
since I send in a pointer?
Because you don't understand how arguments are passed to functions.
This is covered not only in the FAQ, but in any elementary C textbook.