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 = "10.0.0.138"; 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; }
regexec() Function in C
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.
Syntax for regexec() Function in C
#include <regex.h> int regexec(const regex_t *preg, const char *string, size_t nmatch, regmatch_t *pmatch, int eflags);
preg
preg is a pointer to a compiled regular expression to compare against STRING.
string
string is a pointer to a string to be matched.
nmatch
nmatch is the number of sub-expressions to match.
pmatch
pmatch is an array of offsets into STRING which matched the corresponding sub-expressions in preg.
eflags
eflags is a bit flag defining customizable behavior of regexec(). If a match is found, regexec() returns 0. If unsuccessful, regexec() returns nonzero indicating either no match or an error. REG_NOTBOL Indicates that the first character of STRING is not the beginning of the line. REG_NOTEOL Indicates that the first character of STRING is not the end of the line. If nmatch parameter is 0 or REG_NOSUB was set on the call to regcomp(), regexec() ignores the pmatch argument. Otherwise, the pmatch argument points to an array of at least nmatch elements. The regexec() function fills in the elements of the array with offsets of the substrings of STRING that correspond to the parenthesized sub-expressions of the original pmatch specified to regcomp(). The 0th element of the array corresponds to the entire pattern. If there are more than nmatch sub-expressions, only the first nmatch-1 are recorded. When matching a basic or extended regular expression, any given parenthesized sub-expression of pmatch might participate in the match of several different substrings of STRING. The following rules determine which substrings are reported in pmatch. • If a sub-expression participated in a match several times, the offset of the last matching substring is reported in pmatch. • If a sub-expression did not match in the source STRING, the offset shown in pmatch is set to -1. • If a sub-expression contains sub-expressions, the data in pmatch refers to the last such sub-expression. • If a sub-expression matches a zero-length string, the offsets in pmatch refer to the byte immediately following the matching string. If EREG_NOSUB was set when regcomp() was called, the contents of pmatch are unspecified. If REG_NEWLINE was set when regcomp() was called, newline characters are allowed in STRING. With z/OS® XL C/C++, the string passed to the regexec() function is assumed to be in the initial shift state, unless REG_NOTBOL is specified. If REG_NOTBOL is specified, the shift state used is the shift state after the last call to the regexec() function. The information returned by the regexec() function in the regmatch_t structure has the shift-state at the start and end of the string added. This will assist an application to perform replacements or processing of the partial string. To perform replacements, the application must add the required shift-out and shift-in characters where necessary. No library functions are available to assist the application. If MB_CUR_MAX is specified as 4, but the charmap file does not specify the DBCS characters, and a collating-element (for example, [:a:]) is specified in the pattern, the DBCS characters will not match against the collating-element even if they have an equivalent weight to the collating-element.
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
/* This example compiles an extended regular expression, and match against a string. */ #include <regex.h> #include <locale.h> #include <stdio.h> #include <stdlib.h> main() { regex_t preg; char *string = "a simple string"; char *pattern = ".*(simple).*"; int rc; size_t nmatch = 2; regmatch_t pmatch[2]; if ((rc = regcomp(&preg, pattern, REG_EXTENDED)) != 0) { printf("regcomp() failed, returning nonzero (%d)\n", rc); exit(1); } if ((rc = regexec(&preg, string, nmatch, pmatch, 0)) != 0) { printf("failed to ERE match '%s' with '%s',returning %d.\n", string, pattern, rc); } regfree(&preg); }
#ifdef Directive in C
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.
Syntax for #ifdef Directive in C
#ifdef MACRO controlled text #endif /* macroname */
Note: The #ifdef directive must be closed by an #endif directive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* the #ifdef directive allows for conditional compilation. The preprocessor determines if the provided macro exists before including the subsequent code in the compilation process. */ #include<stdio.h> #define PI 3.14 int compute_area(int radius) { return 3.14*radius*radius; } void main() { int area=0, radius=10; #ifdef PI area = compute_area(radius); #else area = 200; #endif printf("\nArea of circle: %d", area); }
fprintf() Function in C
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.
Syntax for fprintf() Function in C
#include <stdio.h> int fprintf ( FILE * stream, const char * format, ... );
stream
Pointer to a FILE object that identifies an output stream.
format
C string that contains the text to be written to the stream. It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested. A format specifier follows this prototype: %[flags][width][.precision][length]specifier Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
specifier
a conversion format specifier.
d or i
Signed decimal integer
u
Unsigned decimal integer
o
Unsigned octal
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (uppercase)
f
Decimal floating point, lowercase
F
Decimal floating point, uppercase
e
Scientific notation (mantissa/exponent), lowercase
E
Scientific notation (mantissa/exponent), uppercase
g
Use the shortest representation: %e or %f
G
Use the shortest representation: %E or %F
a
Hexadecimal floating point, lowercase
A
Hexadecimal floating point, uppercase
c
Character
s
String of characters
p
Pointer address
n
Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location.
%
A % followed by another % character will write a single % to the stream. The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
flags
one or more flags that modifies the conversion behavior (optional)
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
width
an optional * or integer value used to specify minimum width field.
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.precision
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
.number
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
length
an optional length modifier that specifies the size of the argument.
h
The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).
l
The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.
L
The argument is interpreted as a long double (only applies to floating point specifiers - e, E, f, g and G).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function. On success, the total number of characters written is returned. If a writing error occurs, the error indicator (ferror) is set and a negative number is returned. If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.
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
/* write the C string pointed by format to the stream by fprintf() function example */ #include <stdio.h> void main() { FILE *fptr; int id; char name[30]; float salary; fptr = fopen("emp.txt", "w+");/* open for writing */ if (fptr == NULL) { printf("File does not exists \n"); return; } printf("Enter the id\n"); scanf("%d", &id); fprintf(fptr, "Id= %d\n", id); printf("Enter the name \n"); scanf("%s", name); fprintf(fptr, "Name= %s\n", name); printf("Enter the salary\n"); scanf("%f", &salary); fprintf(fptr, "Salary= %.2f\n", salary); fclose(fptr); }
printf() Function in C
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, but are sufficient for many purposes.
Syntax for printf() function in C
#include <stdio.h> int printf ( const char * format, ... );
format
C string that contains the text to be written to stdout. It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested. A format specifier follows this prototype: [see compatibility note below] %[flags][width][.precision][length]specifier Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
specifier
a conversion format specifier.
d or i
Signed decimal integer
u
Unsigned decimal integer
o
Unsigned octal
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (uppercase)
f
Decimal floating point, lowercase
F
Decimal floating point, uppercase
e
Scientific notation (mantissa/exponent), lowercase
E
Scientific notation (mantissa/exponent), uppercase
g
Use the shortest representation: %e or %f
G
Use the shortest representation: %E or %F
a
Hexadecimal floating point, lowercase
A
Hexadecimal floating point, uppercase
c
Character
s
String of characters
p
Pointer address
n
Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location.
%
A % followed by another % character will write a single % to the stream. The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
flags
one or more flags that modifies the conversion behavior (optional)
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
width
an optional * or integer value used to specify minimum width field.
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.precision
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
.number
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
length
an optional length modifier that specifies the size of the argument.
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function. If a writing error occurs, the error indicator (ferror) is set and a negative number is returned. If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.
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
/* print formatted data to stdout by printf() function example */ #include <stdio.h> int main() { char ch; char str[100]; int a; float b; printf("Enter any character \n"); scanf("%c", &ch); printf("Entered character is %c \n", ch); printf("Enter any string ( upto 100 character ) \n"); scanf("%s", &str); printf("Entered string is %s \n", str); printf("Enter integer and then a float: "); // Taking multiple inputs scanf("%d%f", &a, &b); printf("You entered %d and %f", a, b); return 0; }
Continue Statement in C
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.
Syntax for Continue Statement in C
//loop statements continue; //some lines of the code which is to be skipped
The continue statement in C language is used to bring the program control to the beginning of the loop. The continue statement skips some lines of code inside the loop and continues with the next iteration. It is mainly used for a condition so that we can skip some code for a particular condition.
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
/* The continue statement skips the current iteration of the loop and continues with the next iteration. */ // Program to calculate the sum of numbers (10 numbers max) // If the user enters a negative number, it's not added to the result #include <stdio.h> int main() { int i; double number, sum = 0.0; for (i = 1; i <= 10; ++i) { printf("Enter a n%d: ", i); scanf("%lf", &number); if (number < 0.0) { continue; } sum += number; // sum = sum + number; } printf("Sum = %.2lf", sum); return 0; }
Assignment Operators in C
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.
-=
Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.
*=
Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.
/=
Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.
%=
Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.
<<=
Left shift AND assignment operator.
>>=
Right shift AND assignment operator.
&=
Bitwise AND assignment operator.
^=
Bitwise exclusive OR and assignment operator.
|=
Bitwise inclusive OR and assignment operator.
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
/* assignment operators in C language */ #include <stdio.h> main() { int a = 23; int c ; c = a; printf("Line 1 - = Operator Example, Value of c = %d\n", c ); c += a; printf("Line 2 - += Operator Example, Value of c = %d\n", c ); c -= a; printf("Line 3 - -= Operator Example, Value of c = %d\n", c ); c *= a; printf("Line 4 - *= Operator Example, Value of c = %d\n", c ); c /= a; printf("Line 5 - /= Operator Example, Value of c = %d\n", c ); c = 120; c %= a; printf("Line 6 - %= Operator Example, Value of c = %d\n", c ); c <<= 2; printf("Line 7 - <<= Operator Example, Value of c = %d\n", c ); c >>= 2; printf("Line 8 - >>= Operator Example, Value of c = %d\n", c ); c &= 2; printf("Line 9 - &= Operator Example, Value of c = %d\n", c ); c ^= 2; printf("Line 10 - ^= Operator Example, Value of c = %d\n", c ); c |= 2; printf("Line 11 - |= Operator Example, Value of c = %d\n", c ); }
While Loop Statement in C
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.
Syntax of While Loop Statement in C
while (testExpression) { // the body of the loop }
• The while loop evaluates the testExpression inside the parentheses (). • If testExpression is true, statements inside the body of while loop are executed. Then, testExpression is evaluated again. • The process goes on until testExpression is evaluated to false. • If testExpression is false, the loop terminates (ends).
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
/* while loop statement in C language */ #include<stdio.h> int main() { int n, num, sum = 0, remainder; printf("Enter a number: "); scanf("%d", &n); num = n; // keep looping while n > 0 while( n > 0 ) { remainder = n % 10; // get the last digit of n sum += remainder; // add the remainder to the sum n /= 10; // remove the last digit from n } printf("Sum of digits of %d is %d", num, sum); // signal to operating system everything works fine return 0; }
#if, #else and #elif Directives in C
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.
Syntax for #if, #else and #elif Directives in C
#if macro_condition statements #elif macro_condition statements #else statements #endif
Notice how the entire structure of #if, #elif and #else chained directives ends with #endif.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* The pre-processor directives #if, #elif, #else, #endif are used as conditional compilation, whenever we need to compile specify code segments, we use these pre-processor directives. */ #include <stdio.h> #define ENG_US 1 #define ENG_UK 2 #define FRENCH 3 #define LANGUAGE ENG_UK int main(){ #if LANGUAGE==ENG_US printf("Selected language is: ENG_US\n"); #elif LANGUAGE==ENG_UK printf("Selected language is: ENG_UK\n"); #else printf("Selected language is: FRENCH\n"); #endif return 0; }
setlocale() Function in C
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. On program startup, the locale selected is the "C" locale, which is the same as would be set by calling setlocale(LC_ALL,"C"). The locale settings selected in the environment can be selected by calling setlocale(LC_ALL,""). The portions of the current locale affected by a call to this function are specified by argument category.
Syntax for setlocale() Function in C
#include <locale.h> char* setlocale (int category, const char* locale);
category
Portion of the locale affected. It is one of the following constant values defined as macros in :
LC_ALL
Selects all the C locale
LC_COLLATE
Selection the collation category
LC_CTYPE
Selects the character classification category
LC_MONETARY
Selects the monetary formatting category
LC_NUMERIC
Selects the numeric formatting category
LC_TIME
Selects the time formatting category
LC_MESSAGES
specify the language to be used for messages.
locale
C string containing the name of a C locale. These are system specific, but at least the two following locales must exist:
"C"
Minimal "C" locale
""
Environment's default locale If the value of this parameter is NULL, the function does not make any changes to the current locale, but the name of the current locale is still returned by the function. On success, function returns a pointer to a C string identifying the locale currently set for the category. If category is LC_ALL and different portions of the locale are set to different values, the string returned gives this information in a format which may vary between library implementations. If the function failed to set a new locale, this is not modified and a null pointer is returned.
Data races
Changing locale settings may introduce data races with concurrent calls to the same function or to any C-library function affected by the locale.
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
/* set or retrieve locale by setlocale() function code example */ #include <stdio.h> #include <locale.h> int main(int argc, const char * argv[]) { /* Define a temporary variable */ struct lconv *loc; /* Set the locale to the POSIX C environment */ setlocale (LC_ALL, "C"); /* Retrieve a pointer to the current locale */ loc = localeconv(); /* Display some of the locale settings */ printf("Thousands Separator: %s\n", loc->thousands_sep); printf("Currency Symbol: %s\n", loc->currency_symbol); /* Set the locale to the environment default */ setlocale (LC_ALL, ""); /* Retrieve a pointer to the current locale */ loc = localeconv(); /* Display some of the locale settings */ printf("Thousands Separator: %s\n", loc->thousands_sep); printf("Currency Symbol: %s\n", loc->currency_symbol); return 0; }
#define Directive in C
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.
Syntax for #define Directive in C
#define NAME value /* this syntax creates a constant using define*/ // Or #define NAME (expression) /* this syntax creates a constant using define*/
NAME
is the name of a particular constant. It can either be defined in smaller case or upper case or both. Most of the developers prefer the constant names to be in the upper case to find the differences.
value
defines the value of the constant.
Expression
is the value that is assigned to that constant which is defined. The expression should always be enclosed within the brackets if it has any operators. In the C programming language, the preprocessor directive acts an important role within which the #define directive is present that is used to define the constant or the micro substitution. The #define directive can use any of the basic data types present in the C standard. The #define preprocessor directive lets a programmer or a developer define the macros within the source code. This macro definition will allow the constant value that should be declared for the usage. Macro definitions cannot be changed within the program's code as one does with other variables, as macros are not variables. The #define is usually used in syntax that created a constant that is used to represent numbers, strings, or other expressions. The #define directive should not be enclosed with the semicolon(;). It is a common mistake done, and one should always treat this directive as any other header file. Enclosing it with a semicolon will generate an error. The #define creates a macro, which is in association with an identifier or is parameterized identifier along with a token string. After the macro is defined, then the compiler can substitute the token string for each occurrence of the identifier within the source file.
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
/* #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. */ #include <stdio.h> #include <string.h> typedef struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } Book; int main( ) { Book book; strcpy( book.title, "C Programming"); strcpy( book.author, "XCoder"); strcpy( book.subject, "C Programming Tutorial"); book.book_id = 6495407; printf( "Book title : %s\n", book.title); printf( "Book author : %s\n", book.author); printf( "Book subject : %s\n", book.subject); printf( "Book book_id : %d\n", book.book_id); return 0; }
main() Function in C
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. Its first function or entry point of the program from where program start executed, program's execution starts from the main. So main is an important function in c , c++ programming language.
Syntax for main() Function in C
void main() { ......... // codes start from here ......... }
void
is a keyword in C language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value. In place of void we can also use int return type of main() function, at that time main() return integer type value.
main
is a name of function which is predefined function in C library. • An operating system always calls the main() function when a programmers or users execute their programming code. • It is responsible for starting and ends of the program. • It is a universally accepted keyword in programming language and cannot change its meaning and name. • A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program. • A main() function is used to invoke the programming code at the run time, not at the compile time of a program. • A main() function is followed by opening and closing parenthesis brackets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* basic c program by main() function example */ #include <stdio.h> #include <conio.h> main() { printf (" It is a main() function "); int fun2(); // jump to void fun1() function printf ("\n Finally exit from the main() function. "); } void fun1() { printf (" It is a second function. "); printf (" Exit from the void fun1() function. "); } int fun2() { void fun1(); // jump to the int fun1() function printf (" It is a third function. "); printf (" Exit from the int fun2() function. "); return 0; }
memset() Function in C
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.
Syntax for memset() Function in C
#include <string.h> void * memset ( void * ptr, int value, size_t num );
ptr
Pointer to the block of memory to fill.
value
Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
num
Number of bytes to be set to the value. size_t is an unsigned integral type. This function returns a pointer to the memory area str. The function memset("memory setter") is a standard library function in C language that sets or fills a memory block semantically with a value.
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
/* fill a block of memory with a particular value by memset() function code example */ #include <stdio.h> #include <string.h> #define LEN 10 int main(void) { char arr[LEN]; int loop; printf("Array elements are (before memset()): \n"); for(loop=0; loop<LEN; loop++) printf("%d ",arr[loop]); printf("\n"); //filling all blocks with 0 memset(arr,0,LEN); printf("Array elements are (after memset()): \n"); for(loop=0; loop<LEN; loop++) printf("%d ",arr[loop]); printf("\n"); //filling first 3 blocks with -1 //and second 3 blocks with -2 //and then 3 blocks with -3 memset(arr,-1,3); memset(arr+3,-2,3); memset(arr+6,-3,3); printf("Array elements are (after memset()): \n"); for(loop=0; loop<LEN; loop++) printf("%d ",arr[loop]); printf("\n"); return 0; }
Break Statement in C
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.
Syntax for Break Statement in C
//loop statement... break;
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter). If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
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
/* bring the program control out of the loop by break keyword */ // Program to calculate the sum of numbers (10 numbers max) // If the user enters a negative number, the loop terminates #include <stdio.h> int main() { int i; double number, sum = 0.0; for (i = 1; i <= 10; ++i) { printf("Enter n%d: ", i); scanf("%lf", &number); // if the user enters a negative number, break the loop if (number < 0.0) { break; } sum += number; // sum = sum + number; } printf("Sum = %.2lf", sum); return 0; }
fflush() Function in C
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). The stream remains open after this call. When a file is closed, either because of a call to fclose or because the program terminates, all the buffers associated with it are automatically flushed.
Syntax for fflush() Function in C
#include <stdio.h> int fflush ( FILE * stream );
stream
Pointer to a FILE object that specifies a buffered stream. This function returns a zero value on success. If an error occurs, EOF is returned and the error indicator is set (i.e. feof).
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
/* clean (or flush) the output buffer and transfer the buffered data into the terminal (in the case of stdout) or disk (throughout the case of file output) by fflush() function example. */ #include <stdio.h> #include <string.h> int main () { char buff[1024]; memset( buff, '\0', sizeof( buff )); fprintf(stdout, "Going to set full buffering on\n"); setvbuf(stdout, buff, _IOFBF, 1024); fprintf(stdout, "HappyCodings.com\n"); fprintf(stdout, "This output will go into buff\n"); fflush( stdout ); fprintf(stdout, "and this will appear when programm\n"); fprintf(stdout, "will come after sleeping 5 seconds\n"); sleep(5); return(0); }
fdopen() Function in C
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.
Syntax for fdopen() Function in C
#include <stdio.h> FILE *fdopen(int fildes, const char *mode);
fildes
The file descriptor that you want to associate with a stream.
mode
The mode specified when filedes was originally opened. For information, see fopen(), except modes begining with w don't cause truncation of the file. The possible values for the positional parameters are:
r
Create a stream to read a text file. The file pointer is set to the beginning of the file.
w
Create a stream to write to a text file. The file pointer is set to the beginning of the file.
a
Create a stream to write, in append mode, at the end of the text file. The file pointer is set to the end of the file.
r+
Create a stream for reading and writing a text file. The file pointer is set to the beginning of the file.
w+
Create a stream for reading and writing a text file. The file pointer is set to the beginning of the file.
a+
Create a stream for reading or writing, in append mode, at the end of the text file. The file pointer is set to the end of the file.
rb
Create a stream to read a binary file. The file pointer is set to the beginning of the file.
wb
Create a stream to write to a binary file. The file pointer is set to the beginning of the file.
ab
Create a stream to write to a binary file in append mode. The file pointer is set to the end of the file.
r+b or rb+
Create a stream for reading and writing a binary file. The file pointer is set to the beginning of the file.
w+b or wb+
Create a stream for reading and writing a binary file. The file pointer is set to the beginning of the file.
a+b or ab+
Create a stream for reading and writing to a binary file in append mode. The file pointer is set to the end of the file. 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. The keyword parameters allowed for fdopen() are the same as those documented in fopen() - Open Files that are for the integrated file system. If fdopen() returns NULL, use close() to close the file. If fdopen() is successful, you must use fclose() to close the stream and file. A file stream for success, or NULL if an error occurs (errno is set). The filedes argument is a file descriptor that was returned by one of accept(), creat(), dup(), dup2(), fcntl(), open(), pipe(), or sopen(). The fdopen() function preserves the offset maximum previously set for the open file description corresponding to filedes. The fdopen() function may fail if:
EBADF
The fildes argument is not a valid file descriptor.
EINVAL
The mode argument is not a valid mode.
EMFILE
{FOPEN_MAX} streams are currently open in the calling process.
EMFILE
{STREAM_MAX} streams are currently open in the calling process.
ENOMEM
Insufficient space to allocate a buffer.
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
/* associates stream with file descriptor by fdopen() function code example */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> int main(void) { long length; int fh; char buffer[20]; FILE *fp; printf("\nCreating sample.dat.\n"); if ((fp= fopen("/sample.dat", "w")) == NULL) { perror(" File was not created: "); exit(1); } fputs("Sample Program", fp); fclose(fp); memset(buffer, '\0', 20); /* Initialize buffer*/ if (-1 == (fh = open("/sample.dat", O_RDWR|O_APPEND))) { perror("Unable to open sample.dat"); exit(1); } if (NULL == (fp = fdopen(fh, "r"))) { perror("fdopen failed"); close(fh); exit(1); } if (14 != fread(buffer, 1, 14, fp)) { perror("fread failed"); fclose(fp); exit(1); } printf("Successfully read from the stream the following:\n%s.\n", buffer); fclose(fp); return 1; /**************************************************************** * The output should be: * * Creating sample.dat. * Successfully read from the stream the following: * Sample Program. */ }
regcomp() Function in C
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.
Syntax for regcomp() Function in C
#include <regex.h> int regcomp(regex_t *_restrict_ preg, const char *_restrict_ pattern, int cflags);
preg
preg is a pointer to a compiled regular expression.
pattern
pattern is a pointer to a character string defining a source regular expression (described below).
cflags
cflags is a bit flag defining configurable attributes of compilation process:
REG_EXTENDED
Support extended regular expressions.
REG_ICASE
Ignore case in match.
REG_NEWLINE
Eliminate any special significance to the newline character.
REG_NOSUB
Report only success or fail in regexec(), that is, verify the syntax of a regular expression. If this flag is set, the regcomp() function sets re_nsub to the number of parenthesized sub-expressions found in pattern. Otherwise, a sub-expression results in an error. If successful, regcomp() returns 0. If unsuccessful, regcomp() returns nonzero, and the content of preg is undefined. The regcomp() function under z/OS XL C/C++ will use the definition of characters according to the current LC_SYNTAX category. The characters, [, ], {, }, |, ^, and $, have varying code points in different encoded character sets. The functions regcomp(), regerror(), regexec(), and regfree() use regular expressions in a similar way to the UNIX awk, ed, grep, and egrep commands. The simplest form of regular expression is a string of characters with no special meaning. The following characters do have special meaning; they are used to form extended regular expressions: . The period symbol matches any one character except the terminal newline character. [character-character] The hyphen symbol, within square brackets, means "through". It fills in the intervening characters according to the current collating sequence. For example, [a-z] can be equivalent to [abc...xyz] or, with a different collating sequence, it can be equivalent to [aAbBcC...xXyYzZ]. [string] A string within square brackets specifies any of the characters in string. Thus [abc], if compared to other strings, would match any that contained a, b, or c. No assumptions are made at compile time about the actual characters contained in the range. {m} {m,} {m,u} Integer values enclosed in {} indicate the number of times to apply the preceding regular expression. m is the minimum number, and u is the maximum number. u must not be greater than RE_DUP_MAX (see limits.h). If you specify only m, it indicates the exact number of times to apply the regular expression. {m,} is equivalent to {m,u}. They both match m or more occurrences of the expression. * The asterisk symbol indicates 0 or more of any characters. For example, [a*e] is equivalent to any of the following: 99ae9, aaaaae, a999e99. $ The dollar symbol matches the end of the string. (Use \n to match a newline character.) character+ The plus symbol specifies one or more occurrences of a character. Thus, smith+ern is equivalent to, for example, smithhhern. [^string] The caret symbol, when inside square brackets, negates the characters within the square brackets. Thus [^abc], if compared to other strings, would fail to match any that contains even one a, b, or c. (expression)$n Stores the value matched by the enclosed regular expression in the (n+1)th ret parameter. Ten enclosed regular expressions are allowed. Assignments are made unconditionally. (expression) Groups a sub-expression allowing an operator, such as *, +, or [].], to work on the sub-expression enclosed in parentheses. For example, (a*(cb+)*)$0. • Do not use multibyte characters. • You can use the ] (right square bracket) alone within a pair of square brackets, but only if it immediately follows either the opening left square bracket or if it immediately follows [^. For example: []-] matches the ] and - characters. • All the preceding symbols are special. You precede them with \ to use the symbol itself. For example, a\.e is equivalent to a.e. • You can use the - (hyphen) by itself, but only if it is the first or last character in the expression. For example, the expression []--0] matches either the ] or else the characters - through 0. Otherwise, use \-.
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
/* compile regular expression by regcomp() function code example */ #include <regex.h> /* * Match string against the extended regular expression in * pattern, treating errors as no match. * * Return 1 for match, 0 for no match. */ int match(const char *string, char *pattern) { int status; regex_t re; if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) { return(0); /* Report error. */ } status = regexec(&re, string, (size_t) 0, NULL, 0); regfree(&re); if (status != 0) { return(0); /* Report error. */ } return(1); }
open() Function in C
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.
Syntax for open() Function in C
#include <fcntl.h> int open(const char *path, int oflag, ... );
path
path to file which you want to use
oflag
How you like to use The file offset used to mark the current position within the file shall be set to the beginning of the file. The file status flags and file access modes of the open file description shall be set according to the value of oflag. Values for oflag are constructed by a bitwise-inclusive OR of flags from the following list, defined in <fcntl.h>. Applications shall specify exactly one of the first three values (file access modes) below in the value of oflag:
O_RDONLY
Open for reading only.
O_WRONLY
Open for writing only.
O_RDWR
Open for reading and writing. The result is undefined if this flag is applied to a FIFO. Any combination of the following may be used:
O_APPEND
If set, the file offset shall be set to the end of the file prior to each write.
O_CREAT
If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, the file shall be created; the user ID of the file shall be set to the effective user ID of the process; the group ID of the file shall be set to the group ID of the file's parent directory or to the effective group ID of the process; and the access permission bits (see <sys/stat.h>) of the file mode shall be set to the value of the third argument taken as type mode_t modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared. When bits other than the file permission bits are set, the effect is unspecified. The third argument does not affect whether the file is open for reading, writing, or for both. Implementations shall provide a way to initialize the file's group ID to the group ID of the parent directory. Implementations may, but need not, provide an implementation-defined way to initialize the file's group ID to the effective group ID of the calling process.
O_DSYNC
Write I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion.
O_EXCL
If O_CREAT and O_EXCL are set, open() shall fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist shall be atomic with respect to other threads executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set, and path names a symbolic link, open() shall fail and set errno to [EEXIST], regardless of the contents of the symbolic link. If O_EXCL is set and O_CREAT is not set, the result is undefined.
O_NOCTTY
If set and path identifies a terminal device, open() shall not cause the terminal device to become the controlling terminal for the process.
O_NONBLOCK
When opening a FIFO with O_RDONLY or O_WRONLY set: • If O_NONBLOCK is set, an open() for reading-only shall return without delay. An open() for writing-only shall return an error if no process currently has the file open for reading. • If O_NONBLOCK is clear, an open() for reading-only shall block the calling thread until a thread opens the file for writing. An open() for writing-only shall block the calling thread until a thread opens the file for reading. When opening a block special or character special file that supports non-blocking opens: • If O_NONBLOCK is set, the open() function shall return without blocking for the device to be ready or available. Subsequent behavior of the device is device-specific. • If O_NONBLOCK is clear, the open() function shall block the calling thread until the device is ready or available before returning. Otherwise, the behavior of O_NONBLOCK is unspecified.
O_RSYNC
Read I/O operations on the file descriptor shall complete at the same level of integrity as specified by the O_DSYNC and O_SYNC flags. If both O_DSYNC and O_RSYNC are set in oflag, all I/O operations on the file descriptor shall complete as defined by synchronized I/O data integrity completion. If both O_SYNC and O_RSYNC are set in flags, all I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.
O_SYNC
Write I/O operations on the file descriptor shall complete as defined by synchronized I/O file integrity completion.
O_TRUNC
If the file exists and is a regular file, and the file is successfully opened O_RDWR or O_WRONLY, its length shall be truncated to 0, and the mode and owner shall be unchanged. It shall have no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-defined. The result of using O_TRUNC with O_RDONLY is undefined. If O_CREAT is set and the file did not previously exist, upon successful completion, open() shall mark for update the st_atime, st_ctime, and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory. If O_TRUNC is set and the file did previously exist, upon successful completion, open() shall mark for update the st_ctime and st_mtime fields of the file. If both the O_SYNC and O_DSYNC flags are set, the effect is as if only the O_SYNC flag was set. If path refers to a STREAMS file, oflag may be constructed from O_NONBLOCK OR'ed with either O_RDONLY, O_WRONLY, or O_RDWR. Other flag values are not applicable to STREAMS devices and shall have no effect on them. The value O_NONBLOCK affects the operation of STREAMS drivers and certain functions applied to file descriptors associated with STREAMS files. For STREAMS drivers, the implementation of O_NONBLOCK is device-specific. If path names the master side of a pseudo-terminal device, then it is unspecified whether open() locks the slave side so that it cannot be opened. Conforming applications shall call unlockpt() before opening the slave side. The largest value that can be represented correctly in an object of type off_t shall be established as the offset maximum in the open file description. Upon successful completion, the function shall open the file and return a non-negative integer representing the lowest numbered unused file descriptor. Otherwise, -1 shall be returned and errno set to indicate the error. No files shall be created or modified if the function returns -1. The open() function shall fail if:
EACCES
Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by oflag are denied, or the file does not exist and write permission is denied for the parent directory of the file to be created, or O_TRUNC is specified and write permission is denied.
EEXIST
O_CREAT and O_EXCL are set, and the named file exists.
EINTR
A signal was caught during open().
EINVAL
The implementation does not support synchronized I/O for this file.
EIO
The path argument names a STREAMS file and a hangup or error occurred during the open().
EISDIR
The named file is a directory and oflag includes O_WRONLY or O_RDWR.
ELOOP
A loop exists in symbolic links encountered during resolution of the path argument.
EMFILE
{OPEN_MAX} file descriptors are currently open in the calling process.
ENAMETOOLONG
The length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}.
ENFILE
The maximum allowable number of files is currently open in the system.
ENOENT
O_CREAT is not set and the named file does not exist; or O_CREAT is set and either the path prefix does not exist or the path argument points to an empty string.
ENOSR
The path argument names a STREAMS-based file and the system is unable to allocate a STREAM.
ENOSPC
The directory or file system that would contain the new file cannot be expanded, the file does not exist, and O_CREAT is specified.
ENOTDIR
A component of the path prefix is not a directory.
ENXIO
O_NONBLOCK is set, the named file is a FIFO, O_WRONLY is set, and no process has the file open for reading.
ENXIO
The named file is a character special or block special file, and the device associated with this special file does not exist.
EOVERFLOW
The named file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.
EROFS
The named file resides on a read-only file system and either O_WRONLY, O_RDWR, O_CREAT (if the file does not exist), or O_TRUNC is set in the oflag argument. The open() function may fail if:
EAGAIN
The path argument names the slave side of a pseudo-terminal device that is locked.
EINVAL
The value of the oflag argument is not valid.
ELOOP
More than {SYMLOOP_MAX} symbolic links were encountered during resolution of the path argument.
ENAMETOOLONG
As a result of encountering a symbolic link in resolution of the path argument, the length of the substituted pathname string exceeded {PATH_MAX}.
ENOMEM
The path argument names a STREAMS file and the system is unable to allocate resources.
ETXTBSY
The file is a pure procedure (shared text) file that is being executed and oflag is O_WRONLY or O_RDWR.
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
/* open or create a file for reading, writing or executing by open() function code example */ // C program to illustrate // open system call #include<stdio.h> #include<fcntl.h> #include<errno.h> extern int errno; int main() { // if file does not have in directory // then file foo.txt is created. int fd = open("foo.txt", O_RDONLY | O_CREAT); printf("fd = %d/n", fd); if (fd ==-1) { // print which type of error have in a code printf("Error Number % d\n", errno); // print program detail "Success or failure" perror("Program"); } return 0; }
#include Directive in C
#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: • Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. • User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor.
Syntax for #include Directive in C
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* #include directive tells the preprocessor to insert the contents of another file into the source code at the point where the #include directive is found. */ // C program to illustrate file inclusion // <> used to import system header file #include <stdio.h> // " " used to import user-defined file #include "process.h" // main function int main() { // add function defined in process.h add(10, 20); // mult function defined in process.h multiply(10, 20); // printf defined in stdio.h printf("Process completed"); return 0; }
regfree() Function in C
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.
Syntax for regfree() Function in C
#include <regex.h> void regfree(regex_t *preg);
preg
A pointer to the regex_t object for the regular expression that you want to free; see regcomp().
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
/* release memory allocated for a regular expression by regfree() function code example */ #include <regex.h> #include <stdio.h> #include <stdlib.h> int main(void) { regex_t preg; char *pattern = ".*(simple).*"; int rc; if (0 != (rc = regcomp(&preg, pattern, REG_EXTENDED))) { printf("regcomp() failed, returning nonzero (%d)\n", rc); exit(EXIT_FAILURE); } regfree(&preg); printf("regcomp() is successful.\n"); return 0; /************************************************************ The output should be similar to: regcomp() is successful. ************************************************************/ }
sizeof() Operator in C
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.
Syntax for sizeof() Operator in C
#include <stdio.h> sizeof (data type)
data type
Where data type is the desired data type including classes, structures, unions and any other user defined data type. Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() operator:
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
/* return the size of a variable by sizeof() operator example */ int main( int argc, char* argv[] ) { printf("sizeof(char) = %d\n", sizeof(char) ); printf("sizeof(short) = %d\n", sizeof(short) ); printf("sizeof(int) = %d\n", sizeof(int) ); printf("sizeof(long) = %d\n", sizeof(long) ); printf("sizeof(long long) = %d\n", sizeof(long long) ); printf("\n"); printf("sizeof(unsigned char) = %d\n", sizeof(unsigned char) ); printf("sizeof(unsigned short) = %d\n", sizeof(unsigned short) ); printf("sizeof(unsigned int) = %d\n", sizeof(unsigned int) ); printf("sizeof(unsigned long) = %d\n", sizeof(unsigned long) ); printf("\n"); printf("sizeof(float) = %d\n", sizeof(float) ); printf("sizeof(double) = %d\n", sizeof(double) ); printf("sizeof(long double) = %d\n", sizeof(long double) ); printf("\n"); int x; printf("sizeof(x) = %d\n", sizeof(x) ); }
If Else If Ladder in C/C++
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.
Syntax of if...else Ladder in C
if (Condition1) { Statement1; } else if(Condition2) { Statement2; } . . . else if(ConditionN) { StatementN; } else { Default_Statement; }
In the above syntax of if-else-if, if the Condition1 is TRUE then the Statement1 will be executed and control goes to next statement in the program following if-else-if ladder. If Condition1 is FALSE then Condition2 will be checked, if Condition2 is TRUE then Statement2 will be executed and control goes to next statement in the program following if-else-if ladder. Similarly, if Condition2 is FALSE then next condition will be checked and the process continues. If all the conditions in the if-else-if ladder are evaluated to FALSE, then Default_Statement will be executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* write a C program which demonstrate use of if-else-if ladder statement */ #include<stdio.h> #include<conio.h> void main() { int a; printf("Enter a Number: "); scanf("%d",&a); if(a > 0) { printf("Given Number is Positive"); } else if(a == 0) { printf("Given Number is Zero"); } else if(a < 0) { printf("Given Number is Negative"); } getch(); }
line() Function in C
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.
Syntax for line() Function in C
#include <graphics.h> void line(int x1, int y1, int x2, int y2);
x1
X coordinate of first point
y1
Y coordinate of first point.
x2
X coordinate of second point.
y2
Y coordinate of second point. This is a predefined function named line which is used to draw a line on the output screen. It takes 4 arguments, first two parameters represent an initial point and the last two arguments are for the final points of the line.
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
/* draw a line from a point(x1,y1) to point(x2,y2) by line() function example */ /*C graphics program to draw a line.*/ #include <graphics.h> #include <conio.h> main() { int gd = DETECT, gm; //init graphics initgraph(&gd, &gm, "C:/TURBOC3/BGI"); /* if you are using turboc2 use below line to init graphics: initgraph(&gd, &gm, "C:/TC/BGI"); */ //draw a line /* line() function description parameter left to right x1: 100 y1: 100 x2: 200 y2: 100 */ line(100,100,200,100); //will draw a horizontal line line(10,10,200,10); //will draw another horizonatl line getch(); closegraph(); return 0; }
For Loop Statement in C
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.
Syntax of For Loop Statement in C
for (initialization; condition test; increment or decrement) { //Statements to be executed repeatedly }
Step 1
First initialization happens and the counter variable gets initialized.
Step 2
In the second step the condition is checked, where the counter variable is tested for the given condition, if the condition returns true then the C statements inside the body of for loop gets executed, if the condition returns false then the for loop gets terminated and the control comes out of the loop.
Step 3
After successful execution of statements inside the body of loop, the counter variable is incremented or decremented, depending on the operation (++ or --).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* for loop statement in C language */ // Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include <stdio.h> int main() { int num, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); // for loop terminates when num is less than count for(count = 1; count <= num; ++count) { sum += count; } printf("Sum = %d", sum); return 0; }
Logical Operators in C
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.
&&
Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
||
Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.
!
Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.
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
/* logical operators in C language */ #include <stdio.h> main() { int a = 4; int b = 23; int c ; if ( a && b ) { printf("Line 1 - Condition is true\n" ); } if ( a || b ) { printf("Line 2 - Condition is true\n" ); } /* lets change the value of a and b */ a = 2; b = 8; if ( a && b ) { printf("Line 3 - Condition is true\n" ); } else { printf("Line 3 - Condition is not true\n" ); } if ( !(a && b) ) { printf("Line 4 - Condition is true\n" ); } }


Declare recursive function to find factorial of a number. First let us give a meaningful name to our function, say fact(). Factorial Function accepts an integer input whose factorial is to
How to reverse copy array in C programming language. This program code shall help you learn one of basics of arrays. We shall copy one array into another array but in reverse.
C program to read elements in a matrix and find sum of lower triangular matrix. How to find sum of lower triangular matrix in C. Find sum of lower triangular matrix, we need to
Program code to access every 2-D Array we requires 2 subscript variables. y - Refers the Row number. x - Refers Column number. a[1][0] refers element belonging to first row
Function expression, array expression, unary minus, structure operators, increment and decrement, one's compliment, left and right shift, size of operator, pointer operators, type
You can 'concatenate two strings' easily using standard library function strcat() but, in this C program 'concatenates two strings' manually without using 'strcat()' function. Calculate the