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 > Miscellaneous Code Examples

Print ip addresses found in text

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
/* Print ip addresses found in text */ #include <stdio.h> #include <regex.h> #include <locale.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #define IPEXPR "([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})" int main(void) { char line[1024]; char *address = NULL; char delim[] = ",:;`/\"+-_(){}[]<>*&^%$#@!?~/|\\= \t\r\n"; int retval = 0; regex_t re; setlocale(LC_ALL, ""); if(regcomp(&re, IPEXPR, REG_EXTENDED) != 0) return 1; while((fgets(line, 1024, stdin)) != NULL) { if(strchr(line, '.') == NULL) continue; address = strtok(line, delim); while(address != NULL) { if(strlen(address) <= 15) if((retval = regexec(&re, address, 0, NULL, 0)) == 0) printf("%s\n", address); address = strtok(NULL, delim); } /* while */ } /* while */ 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; }
strtok() Function in C
Split string into tokens. A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters. On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of the last token as the new starting location for scanning.
Syntax for strtok() Function in C
#include <string.h> char * strtok ( char * str, const char * delimiters );
str
C string to truncate. Notice that this string is modified by being broken into smaller strings (tokens). Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
delimiters
C string containing the delimiter characters. These can be different from one call to another. If a token is found, function returns a pointer to the beginning of the token. Otherwise, a null pointer. A null pointer is always returned when the end of the string (i.e., a null character) is reached in the string being scanned. To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in delimiters (which becomes the beginning of the token). And then scans starting from this beginning of the token for the first character contained in delimiters, which becomes the end of the token. The scan also stops if the terminating null character is found. This end of the token is automatically replaced by a null-character, and the beginning of the token is returned by the function. Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer. The point where the last token was found is kept internally by the function to be used on the next call (particular library implementations are not required to avoid data races).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* divides a string into tokens by strtok() string function code example */ // program for splitting a string // using strtok() #include <stdio.h> #include <string.h> int main() { char str[] = "HappyCodings"; // Returns first token char* token = strtok(str, "-"); // Keep printing tokens while one of the // delimiters present in str[]. while (token != NULL) { printf("%s\n", token); token = strtok(NULL, "-"); } return 0; }
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(); }
gets() Function in C
Get string from stdin. Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached. The newline character, if found, is not copied into str. A terminating null character is automatically appended after the characters copied to str. Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows). The gets() function enables the user to enter some characters followed by the enter key. All the characters entered by the user get stored in a character array. The null character is added to the array to make it a string. The gets() allows the user to enter the space-separated strings. It returns the string entered by the user.
Syntax for gets() Function in C
#include<stdio.h> char * gets ( char * str );
str
Pointer to a block of memory (array of char) where the string read is copied as a C string. On success, the function returns str. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* read characters from the standard input (stdin) and stores them as a C string */ #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { clrscr(); FILE *fp; char fname[20]; printf("Enter filename : "); gets(fname); fp=fopen(fname, "r"); if(fp==NULL) { printf("Error in opening the file..!!\n"); printf("Press any key to exit..\n"); getch(); exit(1); } fclose(fp); getch(); }
#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; }
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; }
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; }
strlen() Function in C
Get string length. Returns the length of the C string str. The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
Syntax for strlen() Function in C
#include <string.h> size_t strlen ( const char * str );
str
C string Function returns the length of string. This should not be confused with the size of the array that holds the string. strlen() function is defined in string.h header file. It doesn't count null character '\0'.
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
/* get the length of the C string str by strlen() function example */ /* Program to find the total length of a String using strlen() */ #include<stdio.h> #include<string.h> int main() { char str1[10]= "01234567"; /* First string */ printf("First String is %s",str1); printf("\n"); int length = strlen(str1); printf("Length of first String is %d", length); printf("\n"); char str2[20]= "String Chapter"; /* Second string */ printf("Second String is %s",str2); printf("\n"); length = strlen(str2); printf("Length of second String is %d", length); return 0; }
Nested Loop Statement in C
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.
Syntax for Nested Loop Statement in C
Outer_loop { Inner_loop { // inner loop statements. } // outer loop statements. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' loop.
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
/* nested loop statement in C language */ // C Program to print all prime factors // of a number using nested loop #include <math.h> #include <stdio.h> // A function to print all prime factors of a given number n void primeFactors(int n) { // Print the number of 2s that divide n while (n % 2 == 0) { printf("%d ", 2); n = n / 2; } // n must be odd at this point. So we can skip // one element (Note i = i +2) for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, print i and divide n while (n % i == 0) { printf("%d ", i); n = n / i; } } // This condition is to handle the case when n // is a prime number greater than 2 if (n > 2) printf("%d ", n); } /* Driver program to test above function */ int main() { int n = 315; primeFactors(n); 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; }
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); }
fgets() Function in C
Get string from stream. Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str. A terminating null character is automatically appended after the characters copied to str. Notice that fgets is quite different from gets: not only fgets accepts a stream argument, but also allows to specify the maximum size of str and includes in the string any ending newline character.
Syntax for fgets() Function in C
#include <stdio.h> char * fgets ( char * str, int num, FILE * stream );
str
Pointer to an array of chars where the string read is copied.
num
Maximum number of characters to be copied into str (including the terminating null-character).
stream
Pointer to a FILE object that identifies an input stream. stdin can be used as argument to read from the standard input. On success, the function returns str. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
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
/* get string from stream by fgets() function example */ #include<stdio.h> #include<stdlib.h> int main() { char str[50]; FILE *fp; fp = fopen("myfile2.txt", "r"); if(fp == NULL) { printf("Error opening file\n"); exit(1); } printf("Testing fgets() function: \n\n"); printf("Reading contents of myfile.txt: \n\n"); while( fgets(str, 30, fp) != NULL ) { puts(str); } fclose(fp); return 0; }
strchr() Function in C
Locate first occurrence of character in string. Search for a given character in a string. Returns a pointer to the first occurrence of character in the C string str. The terminating null-character is considered part of the C string. Therefore, it can also be located in order to retrieve a pointer to the end of a string. The strchr() function returns a pointer to the first occurrence of the character value character in the string addressed by str. If there is no such character in the string, strchr() returns a null pointer. If character is a null character ('\0'), then the return value points to the terminator character of the string addressed by str.
Syntax for strchr() Function in C
#include <string.h> const char * strchr ( const char * str, int character ); char * strchr ( char * str, int character );
str
C string
character
Character to be located. It is passed as its int promotion, but it is internally converted back to char for the comparison. Function returns a pointer to the first occurrence of character in str. If the character is not found, the function returns a null pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* get first occurrence of character in string by strchr() string function code example */ #include <stdio.h> #include <string.h> int main () { char string[55] ="This is a string for testing"; char *p; int k = 1; p = strchr (string,'i'); while (p!=NULL) { printf ("Character i found at position %d\n",p-string+1); printf ("Occurrence of character \"i\" : %d \n",k); printf ("Occurrence of character \"i\" in \"%s\" is \"%s" \ "\"\n",string, p); p=strchr(p+1,'i'); k++; } 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; }
#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; }
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); }


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 program code input any number from user and toggle or invert or flip nth bit of the given number using bitwise operator. Toggling bit means setting a bit in its complement state.
Code add a lnode at the beginning of the list. Reverse the whole list. Display the whole linked list. Insert some numbers. Add a lnode at the beginning of the list. Add new node.
Print an array in reverse order, we shall know the length of the array in advance. We can start an iteration from length value of array to zero and in each iteration we can print...
Program Print Armstrong Numbers between two Integers. In case of an armstrong number of 3 digits, the Sum of Cubes of each digits is equal to the number itself. For example: 407
C Program calculates the GCD and LCM of 2 integers. Here gcd means greatest common divisor. For two integers a and b, if there are any numbers d so that a / d and b / d doesn't