Once Upon a time, I knew ANSI C well enough to get around. Not so much anymore. Someone once sent me a page of 15 exercises for learning a new programming language. While C isn’t new by any definition, I’m still going to try to use these exercises to get myself some learnage.
The first problem is to simply display a series of numbers (1,2,3,4,5….) in an infinite loop and exit when someone hits a certain key. This was not as simple as it should’ve been. My solution follows.
/* * File: main.c * Author: david.kowis * * Created on August 3, 2009, 1:41 PM */#include <stdio.h>#include <stdlib.h>#include <termios.h>#include <unistd.h>#include <sys/time.h>/* * */intmain(intargc,char**argv){//simple app to barf out numbers until someone hit's escape, or it splodesfd_setrfds;structtimevaltv;intretval;intbuf[15];intreadBytes;intx;structtermiosoldt,newt;unsignedintvalue;intkeypress=0;//set up the terminal to not wait for enter keytcgetattr(STDIN_FILENO,&oldt);newt=oldt;newt.c_lflag&=~(ICANON|ECHO);tcsetattr(STDIN_FILENO,TCSANOW,&newt);value=0;while(keypress!=27){//watch STDIN to see when it has inputFD_ZERO(&rfds);FD_SET(0,&rfds);tv.tv_sec=1;tv.tv_usec=0;retval=select(1,&rfds,NULL,NULL,&tv);if(retval==-1){perror("select()");}elseif(retval){puts("Got data!");//got data, read it?readBytes=read(0,buf,15);if(readBytes>0){puts("read some bytes!");for(x=0;x<readBytes;x++){if(buf[x]==27){keypress=27;}}}else{puts("No bytes read!");}}else{puts("No data read");}//keypress = mygetch();printf("Keypress %u -- Number: %u\n",keypress,++value);}//restore terminaltcsetattr(STDIN_FILENO,TCSANOW,&oldt);return(EXIT_SUCCESS);}
I wrote this using Netbeans 6.7 on Windows (BLECK) using cygwin.