Expert C Programming

(Jeff_L) #1

variable errno that is part of ANSI standard C.


If a library or system call encounters problems, it will set errnoto indicate the cause of the
problem. However, the value of errno is only valid if there was a problem—the call will
have some way of indicating this (usually by its return code).


A typical use might be:


errno=0;


if (ioctl(0, FIONREAD, &i)<0) {


if (errno==EBADF) printf("errno: bad file number");


if (errno==EINVAL) printf("errno: invalid


argument");}


You can get as fancy as you like, and encapsulate the checking in a single function that is
called after each system call while you are debugging your program. This really helps a lot
in isolating the errors. The library call perror() will print out an error message when you
know you have one.


If you're interested in single-character I/O like this, you're often also interested in doing other display
control, and the curses library provides various portable routines for both. Curses (think "cursor") is a
library of screen management calls, with implementations on all popular platforms. Rewriting the
main function above to use curses instead of stty gives:


#include <curses.h>


/* uses curses library, and the kbhit() function defined above


*/


main()


{


int c=' ', i=0;


initscr(); / initialize curses functions /


cbreak();


noecho(); / do not echo pressed character /


mvprintw(0, 0, "Press 'q' to quit\n");


refresh();


while (c!='q')


if (kbhit()) {


c = getch(); /* won't block, as we know a character is


waiting */


mvprintw(1, 0, "got char '%c' on iteration %d \n",c, ++i);


refresh();


}


nocbreak();

Free download pdf