C Examples
(March 2004)

strtok

The following small program shows how strtok can parse a string:
#include <string.h>

main(int argc, char **argv)
{
	char *param, *value;
	if (argc != 2) exit(1);

	param = strtok (argv[1], "=");
	while (param != NULL) {
		value = strtok (NULL, ",");
		printf ("[%s] -> [%s]\n", param, value);
		param = strtok (NULL, "=");
	}
}

lseek

To find out the length of a file:
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
	int fd;
	int length;
	
	if (argc != 2) exit(1);
	fd = open(argv[1], O_RDONLY);
	length = lseek(fd, 0, SEEK_END);
	printf("length of %s: %d\n", argv[1], length);
	return 0;
}

va_arg, va_start, va_end

(function with a variable number of arguments)
#include <stdarg.h>

typedef struct {
    int x;
    int y;
} Type1;

void eprint(int n, ...) {
    va_list     list;
    int         i, value;
    Type1       s;

    if (n<=0) return;

    va_start(list, n);
    i=0;
    value = va_arg(list, int);
    printf("arg[%d]=%d\n", i, value);
    i++;
    s = va_arg(list, Type1);
    printf("arg[%d]={%d, %d}\n", i, s.x, s.y);
    va_end(list);
}

main() {
    Type1 my_struct;
    my_struct.x = 55;
    my_struct.y = 99;
    eprint(2, 111, my_struct);
}