Wednesday, January 21, 2009

errno : C Error Handling

Whatever programming you are doing. It's nice to have a feedback if something goes wrong in your program. Basically a c program would capture error message value generated by system's environment. Bellow is a rudimentary function that capture error handling.
#include "error.h"
#include "errno.h"
#include "stdio.h"

void errordisplay(int error)
{
switch (error)
{
case E2BIG : printf("E2BIG");break;
case EACCES : printf("EACCES");break;
case EADDRINUSE : printf("EADDRINUSE");break;
case EADDRNOTAVAIL : printf("EADDRNOTAVAIL");break;
case EAFNOSUPPORT : printf("EAFNOSUPPORT");break;
/*case EAGAIN : printf("EAGAIN");break;*/
case EALREADY : printf("EALREADY");break;
case EBADE : printf("EBADE");break;
case EBADF : printf("EBADF");break;
case EBADFD : printf("EBADFD");break;
case EBADMSG : printf("EBADMSG");break;
case EBADR : printf("EBADR");break;
case EBADRQC : printf("EBADRQC");break;
case EBADSLT : printf("EBADSLT");break;
case EBUSY : printf("EBUSY");break;
case ECANCELED : printf("ECANCELED");break;
case ECHILD : printf("ECHILD");break;
case ECHRNG : printf("ECHRNG");break;
case ECOMM : printf("ECOMM");break;
case ECONNABORTED : printf("ECONNABORTED");break;
case ECONNREFUSED : printf("ECONNREFUSED");break;
case ECONNRESET : printf("ECONNRESET");break;
/*case EDEADLK : printf("EDEADLK");break;*/
case EDEADLOCK : printf("EDEADLOCK");break;
case EDESTADDRREQ : printf("EDESTADDRREQ");break;
case EDOM : printf("EDOM");break;
case EDQUOT : printf("EDQUOT");break;
case EEXIST : printf("EEXIST");break;
case EFAULT : printf("EFAULT");break;
case EFBIG : printf("EFBIG");break;
case EHOSTDOWN : printf("EHOSTDOWN");break;
case EHOSTUNREACH : printf("EHOSTUNREACH");break;
case EIDRM : printf("EIDRM");break;
case EILSEQ : printf("EILSEQ");break;
case EINPROGRESS : printf("EINPROGRESS");break;
case EINTR : printf("EINTR");break;
case EINVAL : printf("EINVAL");break;
case EIO : printf("EIO");break;
case EISCONN : printf("EISCONN");break;
case EISDIR : printf("EISDIR");break;
case EISNAM : printf("EISNAM");break;
case EKEYEXPIRED : printf("EKEYEXPIRED");break;
case EKEYREJECTED : printf("EKEYREJECTED");break;
case EKEYREVOKED : printf("EKEYREVOKED");break;
case EL2HLT : printf("EL2HLT");break;
case EL2NSYNC : printf("EL2NSYNC");break;
case EL3HLT : printf("EL3HLT");break;
case EL3RST : printf("EL3RST");break;
case ELIBACC : printf("ELIBACC");break;
case ELIBBAD : printf("ELIBBAD");break;
case ELIBMAX : printf("ELIBMAX");break;
case ELIBSCN : printf("ELIBSCN");break;
case ELIBEXEC : printf("ELIBEXEC");break;
case ELOOP : printf("ELOOP");break;
case EMEDIUMTYPE : printf("EMEDIUMTYPE");break;
case EMFILE : printf("EMFILE");break;
case EMLINK : printf("EMLINK");break;
case EMSGSIZE : printf("EMSGSIZE");break;
case EMULTIHOP : printf("EMULTIHOP");break;
case ENAMETOOLONG : printf("ENAMETOOLONG");break;
case ENETDOWN : printf("ENETDOWN");break;
case ENETRESET : printf("ENETRESET");break;
case ENETUNREACH : printf("ENETUNREACH");break;
case ENFILE : printf("ENFILE");break;
case ENOBUFS : printf("ENOBUFS");break;
case ENODATA : printf("ENODATA");break;
case ENODEV : printf("ENODEV");break;
case ENOENT : printf("ENOENT");break;
case ENOEXEC : printf("ENOEXEC");break;
case ENOKEY : printf("ENOKEY");break;
case ENOLCK : printf("ENOLCK");break;
case ENOLINK : printf("ENOLINK");break;
case ENOMEDIUM : printf("ENOMEDIUM");break;
case ENOMEM : printf("ENOMEM");break;
case ENOMSG : printf("ENOMSG");break;
case ENONET : printf("ENONET");break;
case ENOPKG : printf("ENOPKG");break;
case ENOPROTOOPT : printf("ENOPROTOOPT");break;
case ENOSPC : printf("ENOSPC");break;
case ENOSR : printf("ENOSR");break;
case ENOSTR : printf("ENOSTR");break;
case ENOSYS : printf("ENOSYS");break;
case ENOTBLK : printf("ENOTBLK");break;
case ENOTCONN : printf("ENOTCONN");break;
case ENOTDIR : printf("ENOTDIR");break;
case ENOTEMPTY : printf("ENOTEMPTY");break;
case ENOTSOCK : printf("ENOTSOCK");break;
/*case ENOTSUP : printf("ENOTSUP");break;*/
case ENOTTY : printf("ENOTTY");break;
case ENOTUNIQ : printf("ENOTUNIQ");break;
case ENXIO : printf("ENXIO");break;
case EOPNOTSUPP : printf("EOPNOTSUPP");break;
case EOVERFLOW : printf("EOVERFLOW");break;
case EPERM : printf("EPERM");break;
case EPFNOSUPPORT : printf("EPFNOSUPPORT");break;
case EPIPE : printf("EPIPE");break;
case EPROTO : printf("EPROTO");break;
case EPROTONOSUPPORT : printf("EPROTONOSUPPORT");break;
case EPROTOTYPE : printf("EPROTOTYPE");break;
case ERANGE : printf("ERANGE");break;
case EREMCHG : printf("EREMCHG");break;
case EREMOTE : printf("EREMOTE");break;
case EREMOTEIO : printf("EREMOTEIO");break;
case ERESTART : printf("ERESTART");break;
case EROFS : printf("EROFS");break;
case ESHUTDOWN : printf("ESHUTDOWN");break;
case ESPIPE : printf("ESPIPE");break;
case ESOCKTNOSUPPORT : printf("ESOCKTNOSUPPORT");break;
case ESRCH : printf("ESRCH");break;
case ESTALE : printf("ESTALE");break;
case ESTRPIPE : printf("ESTRPIPE");break;
case ETIME : printf("ETIME");break;
case ETIMEDOUT : printf("ETIMEDOUT");break;
case ETXTBSY : printf("ETXTBSY");break;
case EUCLEAN : printf("EUCLEAN");break;
case EUNATCH : printf("EUNATCH");break;
case EUSERS : printf("EUSERS");break;
case EWOULDBLOCK : printf("EWOULDBLOCK");break;
case EXDEV : printf("EXDEV");break;
case EXFULL : printf("EXFULL");break;
}
}

int main(void)
{
int err;
FILE *fp = NULL;
if (fp=fopen("SSS","r")==NULL)
{
err = errno;
}
errordisplay(err);
return 0;
}

After compiling and running this program you notice that it will display the error message, wich is originally is an integer value. I copied, pasted and edited that error messages from errno.h header file (/usr/include/errno.h) :

browse@joko-desktop:~/Desktop$ gcc -o errprog.o errprog.c
errprog.c: In function ‘main’:
errprog.c:135: warning: assignment makes pointer from integer without a cast
browse@joko-desktop:~/Desktop$ ./errprog.o
ENOENTbrowse@joko-desktop:~/Desktop$

Hopefully this will help you in catching logical error in long programs that have many interfaces to another entities. WISH YOU LUCK

Tuesday, January 20, 2009

termios : a prelude to serial port programming

If you like to make a serial port program, you need to use functions and structures declared inside /usr/include/termios.h (be aware it uses another header file /usr/include/bits/termios.h). The first thing that you need to understand is a data structure declared inside /usr/include/bits/termios.h :
struct termios
{
tcflag_t c_iflag; /* input mode flags */
tcflag_t c_oflag; /* output mode flags */
tcflag_t c_cflag; /* control mode flags */
tcflag_t c_lflag; /* local mode flags */
cc_t c_line; /* line discipline */
cc_t c_cc[NCCS]; /* control characters */
speed_t c_ispeed; /* input speed */
speed_t c_ospeed; /* output speed */
#define _HAVE_STRUCT_TERMIOS_C_ISPEED 1
#define _HAVE_STRUCT_TERMIOS_C_OSPEED 1
};

Inside that structure we see the names of other types : tcflag_t, cc_t, and speed_t. What they really are of type char and unsigned int :
1.typedef unsigned char cc_t;
2.typedef unsigned int speed_t;
3.typedef unsigned int tcflag_t;

Now lets disect what are inside the termios (These values are declared inside /usr/include/bits/termios.h) :
1. The posibble values for c_iflag
/* c_iflag bits */
#define IGNBRK 0000001
#define BRKINT 0000002
#define IGNPAR 0000004
#define PARMRK 0000010
#define INPCK 0000020
#define ISTRIP 0000040
#define INLCR 0000100
#define IGNCR 0000200
#define ICRNL 0000400
#define IUCLC 0001000
#define IXON 0002000
#define IXANY 0004000
#define IXOFF 0010000
#define IMAXBEL 0020000
#define IUTF8 0040000

2. The possible values for c_oflag :
/* c_oflag bits */
#define OPOST 0000001
#define OLCUC 0000002
#define ONLCR 0000004
#define OCRNL 0000010
#define ONOCR 0000020
#define ONLRET 0000040
#define OFILL 0000100
#define OFDEL 0000200
#if defined __USE_MISC || defined __USE_XOPEN
# define NLDLY 0000400
# define NL0 0000000
# define NL1 0000400
# define CRDLY 0003000
# define CR0 0000000
# define CR1 0001000
# define CR2 0002000
# define CR3 0003000
# define TABDLY 0014000
# define TAB0 0000000
# define TAB1 0004000
# define TAB2 0010000
# define TAB3 0014000
# define BSDLY 0020000
# define BS0 0000000
# define BS1 0020000
# define FFDLY 0100000
# define FF0 0000000
# define FF1 0100000
#endif
#define VTDLY 0040000
#define VT0 0000000
#define VT1 0040000
#ifdef __USE_MISC
# define XTABS 0014000
#endif

3. The possible values for c_cflag :
/* c_cflag bit meaning */
#ifdef __USE_MISC
# define CBAUD 0010017
#endif
#define B0 0000000 /* hang up */
#define B50 0000001
#define B75 0000002
#define B110 0000003
#define B134 0000004
#define B150 0000005
#define B200 0000006
#define B300 0000007
#define B600 0000010
#define B1200 0000011
#define B1800 0000012
#define B2400 0000013
#define B4800 0000014
#define B9600 0000015
#define B19200 0000016
#define B38400 0000017
#ifdef __USE_MISC
# define EXTA B19200
# define EXTB B38400
#endif
#define CSIZE 0000060
#define CS5 0000000
#define CS6 0000020
#define CS7 0000040
#define CS8 0000060
#define CSTOPB 0000100
#define CREAD 0000200
#define PARENB 0000400
#define PARODD 0001000
#define HUPCL 0002000
#define CLOCAL 0004000
#ifdef __USE_MISC
# define CBAUDEX 0010000
#endif
#define B57600 0010001
#define B115200 0010002
#define B230400 0010003
#define B460800 0010004
#define B500000 0010005
#define B576000 0010006
#define B921600 0010007
#define B1000000 0010010
#define B1152000 0010011
#define B1500000 0010012
#define B2000000 0010013
#define B2500000 0010014
#define B3000000 0010015
#define B3500000 0010016
#define B4000000 0010017
#define __MAX_BAUD B4000000
#ifdef __USE_MISC
# define CIBAUD 002003600000 /* input baud rate (not used) */
# define CMSPAR 010000000000 /* mark or space (stick) parity */
# define CRTSCTS 020000000000 /* flow control */
#endif


4. The possible values for c_lflag :
/* c_lflag bits */
#define ISIG 0000001
#define ICANON 0000002
#if defined __USE_MISC || defined __USE_XOPEN
# define XCASE 0000004
#endif
#define ECHO 0000010
#define ECHOE 0000020
#define ECHOK 0000040
#define ECHONL 0000100
#define NOFLSH 0000200
#define TOSTOP 0000400
#ifdef __USE_MISC
# define ECHOCTL 0001000
# define ECHOPRT 0002000
# define ECHOKE 0004000
# define FLUSHO 0010000
# define PENDIN 0040000
#endif
#define IEXTEN 0100000

Saturday, January 17, 2009

gmtime and localtime (time.h)

We need to use structure for displaying local time (one time only). The program bellow uses predefined structure from “time.h”. The structure tm (which is defined in ) as follows:
#ifdef _TIME_H
__BEGIN_NAMESPACE_STD
/* Used by other time functions. */
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/

#ifdef __USE_BSD
long int tm_gmtoff; /* Seconds east of UTC. */
__const char *tm_zone; /* Timezone abbreviation. */
#else
long int __tm_gmtoff; /* Seconds east of UTC. */
__const char *__tm_zone; /* Timezone abbreviation. */
#endif
};

the structure can be read inside the manual for gcc library. Another declarations inside time.h that are interesting are :

__BEGIN_NAMESPACE_STD
/* Return the `struct tm' representation of *TIMER
in Universal Coordinated Time (aka Greenwich Mean Time). */
extern struct tm *gmtime (__const time_t *__timer) __THROW;

/* Return the `struct tm' representation
of *TIMER in the local timezone. */
extern struct tm *localtime (__const time_t *__timer) __THROW;

__END_NAMESPACE_STD

The program bellow uses gmtime(). According to gcc manual it is a functions that converts the calendar time timep (time protocol) to broken-down time representation, expressed in Coordinated Universal Time (UTC) or GMT.

#include "stdio.h"
#include "time.h"
int main()
{
time_t ttrs;
struct tm *ptrti;
time(&ttrs);
ptrti=gmtime(&ttrs);
printf("%d %d %d", ptrti->tm_hour, ptrti->tm_min, ptrti->tm_sec);
return 0;
}

The program above displays local time once. If you need to capture and display time once every second the you will need a loop. Inside this program we use localtime(). According to gcc manual, it is a function that converts the calendar time timep (time protocol) to broken time representation, expressed relative to the user’s specified time zone or local time zone.
#include "time.h"
#include "stdio.h"
int main()
{
int sh;
time_t rt;
struct tm * ti;
while(1)
{
time(&rt);
ti = localtime(&rt);
if (sh != ti->tm_sec) printf("%d %d %d\n", ti->tm_hour, ti->tm_min, ti->tm_sec);
sh = ti->tm_sec;
}
}

Structure

Structure is a bunch of variables bundled together and then is named according to the proper abstraction of the creator. Therefore the name of a structure depends on the creator. Of course the name should be meaningful. The variables may be of the different type. In another languange a structure may be called a record. In my opinion, the most important aspect of structure is for abstraction. Compiling attributes that are important for current activities, and forget about the unimportant things. For example I need to model a student, and what matters to me for deciding his final mark are : StudentId, First Name, Last Name, Assignment, MidExam, and FinalExam. In this example the weight for final mark calculation is 30% of assignment, 30% of MidExam, and 40% of FinalExam. The name of the structure is Student. See the example bellow :
#include "stdio.h"

#include "stdlib.h"

typedef struct

{

char StudentId[5];

char FirstName[20];

char LastName[20];

float Assignment;

float MidExam;

float FinalExam;

} Student;

int main(void)

{

Student os;

float final;

printf("Student Id : ");

scanf("%s", os.StudentId);

printf("First Name : ");

scanf("%s", os.FirstName);

printf("Last Name : ");

scanf("%s", os.LastName);

printf("Assignment : ");

scanf("%f", &os.Assignment);

printf("Mid Term Exam : ");

scanf("%f", &os.MidExam);

printf("Final Exam : ");

scanf("%f", &os.FinalExam);

final = 0.3*os.Assignment+ 0.3*os.MidExam+ 0.4*os.FinalExam;

printf("The Grade for : %s %s %s is %f", os.StudentId, os.FirstName, os.LastName, final);

}

Tuesday, January 13, 2009

Basic Structure of a Program : Iteration

Iteration

The last important construct is itteration. It executes a set of programming statements several times until certain condition is reached. The sentinel condition is usually evaluated by using pre increment and post increment Operation. Lets have a look at the example bellow. It shows the post increment operation in a simple sequential program :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int i = 10;
system("clear");
printf("%d", i++); /*The output of this operation is 10, since the variable is used first and then the value is incremented */
}

Now we are going to have a pre increment operation :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int i = 10;
system("clear");
printf("%d", ++i); /*The output of this operation is 11, since the variable is incremented first and then the value is displayed */
}

Now lets use this operation for controlling a for loop. Example below is post increment :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int j;
system("clear");
for (j=0;j<10;)
{
printf("%d \n", j++);
}
}

The output of the program is : 0 1 2 3 4 5 6 7 8 9. What would happened if the sentinel is pre increment
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int j;
system("clear");
for (j=0;j<10;)
{
printf("%d \n", ++j);
}
}
The output will decidedly different : 1 2 3 4 5 6 7 8 9 10.

Now its time for use to move to the nitty gritty of C programming.

Friday, January 9, 2009

Basic Structure of a Program : Selection

Basic Structure of a Program : Selection
Selection construct in any programming language is for controlling the execution of certain part of an algorithm when certain condition occurs. In C/C++ language this structure is implemented with if/if-else if-else and switch-case statements. For example we decide not to drink tea when it is hot, we eats when we feel hungry, A lecturer decides that a student passes an exam if his mark is more or equal to 60. Bellow is an example of if construct :

First Example : if
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
float floatGrade; /*Declaring a variable for storing a student's grade*/
system("clear");
printf("Student's Mark : -->");
scanf("%f", &floatGrade);
if (floatGrade >= 60.00)
{
printf("Passes\n");
}
else
{
printf("Fails\n");
}
return 0;
}

Second Example : if/else-if/else
In the next example we specify that a student get :
1.Grade C if his mark is more or equal 60 and less than 70
2.Grade B if his mark is more or equal 70 and less than 80
3.Grade A if his mark is more or equal 80 and less or equal than 100
4.Fails if his mark is more or equal 0 and less than 60
5.The program will say that the value is not legal if it is not in the range between 0 and 100.
The sorce code is :
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
float floatGrade; /*Declaring a variable for storing a student's grade*/
system("clear");
printf("Student's Mark : -->");
scanf("%f", &floatGrade);
if (floatGrade >= 60.00 && floatGrade < 70) /*Condition for grade C*/
{
printf("Passes with grade C\n");
}
else if (floatGrade >= 70.00 && floatGrade < 80) /*Condition for grade B*/
{
printf("Passes with grade B\n");
}
else if (floatGrade >= 80.00 && floatGrade <= 100) /*Condition for grade A*/
{
printf("Passes with grade A\n");
}
else if (floatGrade >= 0.00 && floatGrade < 60) /*Condition for Fail*/
{
printf("Fails \n");
}
else /*Specifying that another value outside the range of 0 to 100 is not legal*/
{
printf("Value is not legal\n");
}
return 0;
}

Third Example : switch-case
Another selection type is using switch-case. A switch-case construct consists of :
1.switch key word accompanied by the variable that will be evaluated to determine which program statement that will be executed.
2.program statements inside the switch-case nest.
The example of this statement is that a student will be awarded a sum of money, so that he can go to the movie.
#include "stdio.h"
#include "stdlib.h"
#include "ctype.h" /*We use toupper to convert the lowercase input to uppercase*/
int main()
{
char chrGrade;

system("clear");
printf("Student Grade :---> ");
scanf("%c", &chrGrade);
chrGrade=toupper(chrGrade);
switch(chrGrade)
{
case 'A' : printf("You are awarded $100");break;
case 'B' : printf("You are awarded $50");break;
case 'C' : printf("You are awarded $25");break;
case 'D' : printf("You are awarded $0");break;
default : printf("Wrong Grade");break;
}
return 0;
}

Now you have already learn how to create a selection construct.

Basic Structure of a Program : Sequence

Basically a program(algorithm) have three basic structures : sequence, selection, and repetition. We are going to discussed these basic structures by using examples. So that you will have basic and hopefully thorough knowledge of each structure.

Sequence
A Sequence consists of several instructions. Each instruction is executed according to its writing order. Instruction sequence determines the result of an algorithm. This is a sample of simple algorithm :
1.Put the pan on the stove
2.Turn on the stove
3.Put the butter into the pan
4.Pour in egg
5.Let it fried for a minute
6.Put the egg on a plate
Now you can have a plate of EATABLE fried egg. What would happen if you change the order. for example :
1.Put the pan on the stove
2.Turn on the stove
3.Pour in egg
4.Let it fried for a minute
5.Put the butter into the pan
6.Put the egg on a plate.
What do we have know ? BURNT UNEATABLE BITTER UGLY fried egg. Now lets have a simple program that can be compiled by using gcc compiler.

First Example : HELLO World
The example will produce simple executable binary file. Now we have a file named hello.c :

#include "stdio.h"

int main()
{
printf("Hello World");
return 0;
}

Then we need to do a compilation with statement like this :
#gcc -o hello.out hello.c

The output of this statement is hello.out, We can execute this executable by issuing this command :
#./hello.out

Afterwards the output "Hello World" will be displayed

More example
Lets make another simple program that will takes user input for calculating the area of a triangle. The source code is listed bellow :

#include "stdio.h"
#include "stdlib.h"
int main(void)
{
float floatHeight = 0, floatWidth = 0;
system("clear"); /* This statement calls system's command : “clear” */
printf("\nWidth : --> ");
scanf("%f", &floatHeight);
printf("\nHeight : --> ");
scanf("%f", &floatWidth);
printf("\nArea : --> %f", floatHeight*floatWidth/2);
return 0;
}

Another example will be nice to enhance our "felling" for writing a program in sequential construct. The program is about calculating the area of a circle :
#include "stdlib.h"
#include "stdio.h"
#define PI 3.1416
int main()
{
float rad;
float area;
system("clear");
printf("Enter radius :-> ");
scanf("%f", &rad);
area = PI * rad * rad;
printf("Area :---------> %f", area);
printf("\nBye...");
return 0;
}

Another example is calculating the area of a rectangle :
#include "stdio.h"
#include "stdlib.h"
int main()
{
float width,length;
float area;
system("clear");
printf("Length :-> ");
scanf("%f", &length);
printf("Width :-> ");
scanf("%f", &width);
printf("Area :-> %f\n", length*width);
return 0;
}

We are going to have another simple example of sequence. See the source code bellow for the calculation of a volume of a cylinder :
#include "stdio.h"
#include "stdlib.h"
#include "math.h" /*contains prototype of pow (power) */
int main(void)
{
float floatHeight = 0, floatRadius = 0;
system("clear");
printf("\nHeight : --> ");
scanf("%f", &floatHeight);
printf("\nRadius : --> ");
scanf("%f", &floatRadius);
printf("\nVolume : --> %f", floatHeight*pow(floatRadius,2)*22/7);
return 0;
}
So, business as usual, compile and run it !!!