Hi
Could someone give me a simple example of a callback in C? I want to have a function that after I set running it calls another function once it has completed.
Many thanks
David
Hi
Could someone give me a simple example of a callback in C? I want to have a function that after I set running it calls another function once it has completed.
Many thanks
David
Read up on quicksort, it's API uses a callback. Here's one link: http://www.cppreference.com/wiki/c/other/qsort
Mainframe assembler programmer by trade. C coder when I can.
Example:
And your callback function would just be streaming in the contents of the file.Code:#define BUFSIZE 4096 typedef int (*do_stuff)(void *, size_t); int readfile(const char *filename, do_stuff func) { FILE *file = fopen(filename, "rb"); void *buffer = malloc(BUFSIZE); if(!buffer | !file) /* Gracias a mi amigo robwhit */ { if(buffer) free(buffer); if(file) fclose(file); return 0; } while(fread(buffer, BUFSIZE, 1, file)) func(buffer, BUFSIZE); return 1; }
Last edited by master5001; 10-03-2008 at 01:01 PM. Reason: Logic error in an if statement corrected.
If malloc succeeds and fopen fails, the failure would not be detected due to the short-circuiting of the || operator. To fix it, do this instead:Code:FILE *file = fopen(filename, "rb"); void *buffer = malloc(BUFSIZE); if(!buffer || !file)Or this:Code:if (buffer && file)Code:if (!buffer | !file)
Last edited by robwhit; 10-03-2008 at 12:24 PM.
Oops, good observation. However it should still actually be:
Good catch.Code:if(!(buffer && file))
> Good catch.
likewise.