Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes

C Programming Code Examples

C > Small Programs Code Examples

Collect [line] stats from SpeedTouch 510 ADSL modem

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
/* Collect [line] stats from SpeedTouch 510 ADSL modem */ #include <stdio.h> #include <unistd.h> #include <error.h> #include <errno.h> #include <signal.h> #include <sys/time.h> #include <sys/types.h> #include <netdb.h> #include <sys/socket.h> #include <regex.h> #include <locale.h> #define MAXLINE 1024 static int alarm_flag = 0; static struct sigaction act1, oact1; int input_timeout(int, unsigned int); int readline(int, char *, size_t); int mkconnectsock(char *, int, int); void alarm_function(int); void isip4addr(char *); int main(int argc, char *argv[]) { FILE *fpout = {0}; char line[MAXLINE]; char c; char *ptr = NULL; char *ipaddr = ""; char *comtab[2] = { "adsl info", "exit" }; int comtabsize = 2; int ipport = 23; int conntimeout = 10; int sockid, bread; int i, state; i = state = 0; /* this is a quick hack.. Not a program...! */ if(argc == 1) error(1, 0, "Usage: %s ip4address", "adslinfo"); else { isip4addr(argv[1]); ipaddr = argv[1]; } /* connect & setup write descrip. */ sockid = mkconnectsock(ipaddr, ipport, conntimeout); if((fpout = fdopen(sockid, "w")) == NULL) error(1, 0, "Error - fdopen()"); /* skipping the first [telnet] connection block.. */ /* SOH ETX SOH ETX */ /* 377 373 001 377 373 003 377 373 001 377 373 003 */ for(i = 0; i < 12; i++) if((bread = recv(sockid, &c, 1, 0)) == -1) error(1, 0, "Error - recv(): first 12 bytes"); /* w're not event driven.. */ fprintf(fpout, "%s", "\r\f"), fflush(fpout); fprintf(fpout, "%s", "\r\f"), fflush(fpout); /* issue commands */ for(i = 0; i < comtabsize; i++) { fprintf(fpout, "%s\r\f", comtab[i]), fflush(fpout); while(readline(sockid, line, sizeof(line)) > 0) { if(line[0] == '=' && line[1] == '>') break; if(line[0] == 'M' && line[1] == 'o') state = 1; if(state == 1) for(ptr = line; *ptr; ptr++) if(*ptr != '\r') printf("%c", *ptr); } } return 0; } int mkconnectsock(char *ipstr, int port, int tmout) { int sockid = -1; struct sockaddr_in pin; struct hostent *nlp_host; if((nlp_host = gethostbyname(ipstr)) == 0) error(1, 0, "Error - resolving host: %s", ipstr); memset(&pin, '\0', sizeof(pin)); pin.sin_family = AF_INET; pin.sin_addr.s_addr = htonl(INADDR_ANY); pin.sin_addr.s_addr = ((struct in_addr *)(nlp_host->h_addr))->s_addr; pin.sin_port = htons(port); if((sockid = socket(AF_INET, SOCK_STREAM, 0)) < 0) error(1, 0, "Error - socket(%d)", sockid); /* set up alarm */ act1.sa_handler = alarm_function; sigemptyset(&act1.sa_mask); act1.sa_flags = 0; #ifdef SA_INTERRUPT act1.sa_flags |= SA_INTERRUPT; #endif if(sigaction(SIGALRM, &act1, &oact1) < 0) error(1, 0, "Error - sigaction()"); /* connect .... */ alarm(tmout); if(connect(sockid, (void *)&pin, sizeof(pin)) != 0) error(1, 0, "Error - connect()"); alarm(0); /* interrupted connect */ if(alarm_flag == 1) error(1, 0, "Error - connect(): timeout"); return sockid; } int input_timeout(int filedes, unsigned int seconds) { fd_set set; struct timeval timeout; FD_ZERO(&set); FD_SET(filedes, &set); timeout.tv_sec = seconds; timeout.tv_usec = 0; /* `0' on: timeout, `1' on: input available, `-1' on: error */ return select(FD_SETSIZE, &set, NULL, NULL, &timeout); } void alarm_function(int signo) { alarm_flag = 1; } void isip4addr(char *str) { char ipexpr[] = "^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$"; regex_t re = {0}; setlocale(LC_ALL, ""); if(regcomp(&re, ipexpr, REG_EXTENDED) != 0) error(1, 0, "Error - Unable to compile regex:\n%s\n", ipexpr); if(regexec(&re, str, 0, NULL, 0) != 0) error(1, 0, "Error - Invalid ip4 address: %s", str); regfree(&re); return; } int readline(int fd, char *bufptr, size_t len) { char *bufx = bufptr; static char *bp; static int cnt = 0; static char b[1500]; char c; while(--len > 0) { if(--cnt <= 0) { cnt = recv(fd, b, sizeof(b), 0); if(cnt < 0) { if(errno == EINTR) { len++; continue; } return -1; } if(cnt == 0) return 0; bp = b; } c = *bp++; *bufptr++ = c; if(c == '\n') { *bufptr = '\0'; return bufptr - bufx; } } return -1; }

This is function is used for matching the string with the given pattern of the string. This also has 5 arguments like precompiled pattern, the second parameter which will take string which needs to be searched for, the third parameter contains the details of the location of matches, the fourth parameter contains details of searches, and the fifth parameter contains the flag which gives the indication the change in the matching behavior. This regexec() function returns 0 if there is successful matching done and REG_NOMATCH if the string does not match. Compares the NULL-terminated string specified by string against the compiled regular expression, preg.

This directive is the simplest conditional directive. This block is called a conditional group. The controlled text will get included in the preprocessor output iff the macroname is defined. The controlled text inside a conditional will embrace preprocessing directives. They are executed only if the conditional succeeds. You can nest these in multiple layers, but they must be completely nested. In other words, '#endif' always matches the nearest '#ifdef' (or '#ifndef', or '#if'). Also, you can't begin a conditional group in one file and finish it in another.

Write formatted data to stream. Writes the C string pointed by format to the stream. If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. After the format parameter, the function expects at least as many additional arguments as specified by format.

Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers,

The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control to pass to the conditional tests.

Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language: Simple assignment operator. Assigns values from right side operands to left side operand. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.

These directives works together and control compilation of portions of the program using some conditions. If the condition with the #if directive evaluates to a non zero value, then the group of line immediately after the #if directive will be executed otherwise if the condition with the #elif directive evaluates to a non zero value, then the group of line immediately after the #elif directive will be executed else the lines after #else directive will be executed.

Set or retrieve locale. Sets locale information to be used by the current program, either changing the entire locale or portions of it. The function can also be used to retrieve the current locale's name by passing NULL as the value for argument locale. Locales contain information on how to interpret and perform certain input/output and transformation operations taking into consideration location and language specific settings. Most running environments have certain locale information set according to the user preferences or localization. But, independently of this system locale, on start, all C programs have the "C" locale set, which is a rather neutral locale with minimal locale information that allows the result of programs to be predictable. In order to use the default locale set in the environment, this function can be called with "" as argument locale.

In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.

In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed.

Fill block of memory. Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char). The C library function copies the character value (an unsigned char) to the first num characters of the string pointed to, by the argument ptr. This function returns a pointer to the memory area ptr. This function returns a pointer to the memory area str.

The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.

Flush stream. If the given stream was open for writing (or if it was open for updating and the last i/o operation was an output operation) any unwritten data in its output buffer is written to the file. If stream is a null pointer, all such streams are flushed. In all other cases, the behavior depends on the specific library implementation. In some implementations, flushing a stream open for reading causes its input buffer to be cleared (but this is not portable expected behavior).

Associate a stream with a file descriptor. The fdopen() function associates an input or output stream with the file that is identified by fildes. The mode variable is a character string specifying the type of access that is requested for the stream. The variable contains one positional parameter that is followed by optional keyword parameters. Use the w, w+, wb, wb+, and w+b modes with care; they can destroy existing files. The specified type must be compatible with the access method you used to open the file. If the file was opened with the O_APPEND flag, the stream mode must be a, a+, ab, a+b, or ab+. To use the fdopen() function you need a file descriptor. To get a descriptor use the POSIX function open(). The O_APPEND flag is a mode for open(). Modes for open() are defined in QSYSINC/H/FCNTL. For further information see the APIs topic in the Information Center.

A regular expression is a sequence of characters used to match a pattern to a string. The expression can be used for searching text and validating input. Remember, a regular expression is not the property of a particular language. POSIX is a well-known library used for regular expressions in C. Patterns in the POSIX library: [] - Used to find any of the characters or numbers specified between the brackets. [:number:] - Used to find any digit. [:lower:] - Used to find lowercase alphabets. [:word:] - Used to find letters numbers and underscores. Compiles the regular expression specified by pattern into an executable string of op-codes.

The open() function shall establish the connection between a file and a file descriptor. It shall create an open file description that refers to a file and a file descriptor that refers to that open file description. The file descriptor is used by other I/O functions to refer to that file. The path argument points to a pathname naming the file. The open() function shall return a file descriptor for the named file that is the lowest file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor shall not share it with any other process in the system. The FD_CLOEXEC file descriptor flag associated with the new file descriptor shall be cleared.

#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include:

Release memory allocated for a regular expression. The regfree() function frees any memory that was allocated by the regcomp() function to implement the regular expression preg. After the call to the regfree() function, the expression that is defined by preg is no longer a compiled regular or extended expression.

The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

line() is a library function of graphics.c in c programming language which is used to draw a line from two coordinates. line() function is used to draw a line from a point(x1,y1) to point(x2,y2) i.e. (x1,y1) and (x2,y2) are end points of the line.

The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.

An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. These operators are used to perform logical operations and used with conditional statements like C if-else statements.

The following 'C Language Program' to using recursion, finds whether the entered number is a prime number or not. A 'prime number' is integer that has no integral factor but itself &

C Input base and height of a triangle and find area of the given triangle. How to find area of a triangle in C programming. Input base of the triangle. Store in some variable say base.

C Program code remove 'trailing white space' characters is 'lot more easier' and faster than removing leading white space characters. As in this case we need not to perform any 'char'

Code Step by Step descriptive logic to check Uppercase and Lowercase alphabets. Input a character from user. Store it in some variable say ch. Character is uppercase alphabet if(ch

In C programming language we use bitwise AND & operator to check status of any bit. Bitwise AND operation evaluate each bit of resultant value as 1, if corresponding bit of...

Go back to normal graphics mode or deleting viewport. Checking the egg position. Display mouse pointer. Define the upper left boundry of mouse. Define the bottom right boundry