Have you checked if these apps could do the job?
Code:
ubuntu-intrepid$ apt-cache search webcam grab
camgrab - A command line tool to download a single image from a webcam
gkrellkam - GKrellM plugin that displays a periodically updating image
gqcam - GTK Webcam control
luvcview - USB Video Class grabber
vgrabbj - grabs a image from a camera and puts it in jpg/png format
If you really want to code it yourself, did you have a look at the source code of these (and/or other) apps?