Thread: Callbacks?

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    58

    Lightbulb Callbacks?

    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

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    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.

  3. #3
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Example:
    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;
    }
    And your callback function would just be streaming in the contents of the file.
    Last edited by master5001; 10-03-2008 at 01:01 PM. Reason: Logic error in an if statement corrected.

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Code:
    FILE *file = fopen(filename, "rb");
    void *buffer = malloc(BUFSIZE);
    
    if(!buffer || !file)
    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:
    if (buffer && file)
    Or this:
    Code:
    if (!buffer | !file)
    Last edited by robwhit; 10-03-2008 at 12:24 PM.

  5. #5
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Oops, good observation. However it should still actually be:

    Code:
    if(!(buffer && file))
    Good catch.

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    > Good catch.

    likewise.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Input via callbacks or functions
    By zacs7 in forum Game Programming
    Replies: 3
    Last Post: 06-02-2008, 05:12 PM
  2. Callbacks to member functions
    By prog-bman in forum C++ Programming
    Replies: 0
    Last Post: 01-19-2008, 02:48 AM
  3. declaring function pointer types for callbacks
    By Pea in forum C Programming
    Replies: 6
    Last Post: 01-06-2005, 09:46 PM
  4. callbacks within a class?
    By btq in forum C++ Programming
    Replies: 5
    Last Post: 10-02-2002, 05:51 AM
  5. Callbacks
    By pradeepkrao in forum C++ Programming
    Replies: 5
    Last Post: 09-13-2002, 10:30 PM