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>

/*
 *
 */
int main(int argc, char** argv) {

    //simple app to barf out numbers until someone hit's escape, or it splodes
    fd_set rfds;
    struct timeval tv;
    int retval;
    int buf[15];
    int readBytes;
    int x;
    struct termios oldt, newt;

    unsigned int value;
    int keypress = 0;

    //set up the terminal to not wait for enter key
    tcgetattr(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 input
        FD_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()");
        } else if (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 terminal
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

    return (EXIT_SUCCESS);
}

I wrote this using Netbeans 6.7 on Windows (BLECK) using cygwin.

  3 Responses to “(re)Learning ANSI C”

Comments (3)
  1. I’m going to note that this blog absolutely sucks at posting code

  2. Pastebin and picture instead?

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2011 Shlrm.org Blag Suffusion theme by Sayontan Sinha