Passing functions as parameters in other functions
Passing functions as parameters
Hello,
I am having trouble understanding how some code works for a project of mine. I don't quite get how passing a function as a parameter into another function works. Here is the code im referring to:
Code:
void tftp_connection(struct sockaddr_in *serveraddr,char *action,char *name, char *readname)
{
FILE *f;
int blen=255;
if ((action[0]=='R')||(action[0]=='r')) {
f=fopen(name,"wb");
if (readname==NULL)
blen=tftp_receive(serveraddr,name,"octet",1,TFTPswrite,f);
else
blen=tftp_receive(serveraddr,readname,"octet",1,TFTPswrite,f);
fclose(f);
}
if (blen!=0)
printf("tftp error. please try again.\n\n");
}
int tftp_receive(struct sockaddr_in *to1,char *name,char *mode,int innum,
char (*TFTPwrite)(char *,long ,char,void *),
void *argu)
{
return tftp_receive_ext(to1,name,mode,innum,TFTPwrite,argu,PKTSIZE);
}
char TFTPswrite(char *data,long n,char first,void *f)
{
fwrite(data,n,1,(FILE *)f);
return 0;
}
The question i have is that when you pass TFTPswrite as a parameter in both:
Code:
blen=tftp_receive(serveraddr,name,"octet",1,TFTPswrite,f);
return tftp_receive_ext(to1,name,mode,innum,TFTPwrite,argu,PKTSIZE);
how does it know what parameters to use for the function since we are just passing the name of the function? TFTPwrite uses data, n, and *f, but when we call the function (tftp_receive and tftp_receive_ext respectively) that passes TFTPswrite as a function where is it pulling these values for TFTPswrite to use from (char *data,long n,char first,void *f)?
I also have a question as to when the code for TFTPswrite executes. Does it execute when it is passed in as a parameter? Would there be another way to not pass TFTPswrite as a parameter and just have the one line of code it uses execute somewhere else in the program so that we can avoid passing it as a parameter?
Any help would be greatly appricated i know it sounds confusing me trying to explain but i think the code is even more confusing.
'