Skip to content

Instantly share code, notes, and snippets.

Created August 8, 2013 03:10
Show Gist options
  • Save anonymous/6181127 to your computer and use it in GitHub Desktop.
Save anonymous/6181127 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
void eachrow(size_t nrows, size_t ncols, char const*** rows, BOOL(^cb)(size_t i, size_t ncols, char const **row, size_t *lengths))
{
size_t lengths[ncols];
for (size_t i = 0; i < nrows; ++i)
{
for (size_t j = 0; j < ncols; ++j)
{
lengths[j] = strlen(rows[i][j]);
}
if (!cb(i, ncols, rows[i], lengths)) break;
}
}
static void print_int(char const *s, size_t l)
{
printf("%d, ", atoi(s));
}
static void print_string(char const *s, size_t l)
{
printf("%.*s, ", (int)l, s);
}
static void print_float(char const *s, size_t l)
{
printf("%f\n", atof(s));
}
int main(int argc, const char * argv[])
{
__block struct
{
void (*fptrs[3])(char const *, size_t);
}
ctx;
eachrow(3, 3, (char const **[]){
(char const *[]){ "1", "hello", "3.14" },
(char const *[]){ "2", "pony", "2.72" },
(char const *[]){ "3", "world", "1.62" },
}, ^(size_t i, size_t ncols, char const **row, size_t *lengths)
{
if (i == 0)
{
ctx.fptrs[0] = print_int;
ctx.fptrs[1] = print_string;
ctx.fptrs[2] = print_float;
}
for (size_t col = 0; col < ncols; ++col)
{
ctx.fptrs[col](row[col], lengths[col]);
}
return YES;
});
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment