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 > Gnu-Linux Code Examples

Using the terminfo database

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Using the terminfo database */ #include <stdio.h> #include <curses.h> #include <term.h> int main(void) { int num_rows = 0, num_columns = 0; setupterm(NULL, fileno(stdout), (int *)0); num_rows = tigetnum("lines"); num_columns = tigetnum("cols"); printf("terminal:\ncolumns: %d\nrows %d\n", num_columns, num_rows); return 0; }
fileno() Function in C
Get the file descriptor from an open stream. The fileno() function returns the number of the file descriptor for the file designated by stream. This number can be used in POSIX input/output calls anywhere the value returned by open() can be used. The following symbolic values in <unistd.h> define the file descriptors that are associated with the C language stdin, stdout, and stderr files when the application is started. Returns the file descriptor number associated with a specified z/OS® XL C/C++ I/O stream. The argument stream points to a FILE structure controlling a z/OS XL C/C++ I/O stream.
Syntax for fileno() Function in C
#include <stdio.h> int fileno( FILE *stream );
stream
The stream whose file descriptor you want to find. • STDIN_FILENO - Standard input file number, stdin (). • STDOUT_FILENO - Standard output file number, stdout (). • STDERR_FILENO - Standard error file number, stderr (). Function returns the number of the file descriptor for the file designated by stream. If an error occurs, a value of -1 is returned, and errno is set to indicate the error. EBADF - One of the following error conditions exists: • stream points to a closed stream • stream is an incorrect stream pointer • stream points to a stream associated with an MVS data set. fileno_unlocked() is functionally equivalent to fileno() with the exception that it is not thread-safe. This function can safely be used in a multithreaded application if and only if it is called while the invoking thread owns the (FILE*) object, as is the case after a successful call to either the flockfile() or ftrylockfile() function. Library: libc - Use the -l c option to qcc to link against this library. This library is usually included automatically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* get the file descriptor for a stream by fileno() function code example */ #include <stdlib.h> #include <stdio.h> int main( void ) { FILE *stream; stream = fopen( "file", "r" ); if( stream != NULL ) { printf( "File number is %d.\n", fileno( stream ) ); fclose( stream ); return EXIT_SUCCESS; } return EXIT_FAILURE; }
setupterm() Function in C
These low-level routines must be called by programs that have to deal directly with the terminfo database to handle certain terminal capabilities, such as programming function keys. For all other functionality, curses routines are more suitable and their use is recommended. Initially, setupterm should be called. Note that setupterm is automatically called by initscr and newterm. This defines the set of terminal-dependent variables [listed in terminfo(5)]. The terminfo variables lines and columns are initialized by setupterm as follows: If use_env(FALSE) has been called, values for lines and columns specified in terminfo are used.
Syntax for setupterm() Function in C
#include <term.h> int setupterm(char *term, int fildes, int *errret);
term
term is the terminal type, a character string. If term is null, the environment variable TERM is used.
filedes
filedes is the file descriptor used for all output.
errret
points to an optional location where an error status can be returned to the caller. If errret is not null, then setupterm returns OK or ERR and stores a status value in the integer pointed to by errret. A return value of OK combined with status of 1 in errret is normal. Otherwise, if the environment variables LINES and COLUMNS exist, their values are used. If these environment variables do not exist and the program is running in a window, the current window size is used. Otherwise, if the environment variables do not exist, the values for lines and columns specified in the terminfo database are used. The header files curses.h and term.h should be included (in this order) to get the definitions for these strings, numbers, and flags. Parameterized strings should be passed through tparm to instantiate them. All terminfo strings [including the output of tparm] should be printed with tputs or putp. Call the reset_shell_mode to restore the tty modes before exiting [see curs_kernel(3X)]. Programs which use cursor addressing should output enter_ca_mode upon startup and should output exit_ca_mode before exiting. Programs desiring shell escapes should call reset_shell_mode and output exit_ca_mode before the shell is called and should output enter_ca_mode and call reset_prog_mode after returning from the shell. The setupterm routine reads in the terminfo database, initializing the terminfo structures, but does not set up the output virtualization structures used by curses. The terminal type is the character string term; if term is null, the environment variable TERM is used. All output is to file descriptor fildes which is initialized for output. If errret is not null, then setupterm returns OK or ERR and stores a status value in the integer pointed to by errret. A return value of OK combined with status of 1 in errret is normal. If ERR is returned, examine errret: 1 - means that the terminal is hardcopy, cannot be used for curses applications. 0 - means that the terminal could not be found, or that it is a generic type, having too little information for curses applications to run. -1 - means that the terminfo database could not be found. If errret is null, setupterm prints an error message upon finding an error and exits. Thus, the simplest call is: setupterm((char *)0, 1, (int *)0);, which uses all the defaults and sends the output to stdout. The setterm routine is being replaced by setupterm. The call: setupterm(term, 1, (int *)0) provides the same functionality as setterm(term). The setterm routine is included here for BSD compatibility, and is not recommended for new programs. The set_curterm routine sets the variable cur_term to nterm, and makes all of the terminfo boolean, numeric, and string variables use the values from nterm. It returns the old value of cur_term. The del_curterm routine frees the space pointed to by oterm and makes it available for further use. If oterm is the same as cur_term, references to any of the terminfo boolean, numeric, and string variables thereafter may refer to invalid memory locations until another setupterm has been called. The restartterm routine is similar to setupterm and initscr, except that it is called after restoring memory to a previous state (for example, when reloading a game saved as a core image dump). It assumes that the windows and the input and output options are the same as when memory was saved, but the terminal type and baud rate may be different. Accordingly, it saves various tty state bits, calls setupterm, and then restores the bits. The tparm routine instantiates the string str with parameters pi. A pointer is returned to the result of str with the parameters applied. The tputs routine applies padding information to the string str and outputs it. The str must be a terminfo string variable or the return value from tparm, tgetstr, or tgoto. affcnt is the number of lines affected, or 1 if not applicable. putc is a putchar-like routine to which the characters are passed, one at a time. The putp routine calls tputs(str, 1, putchar). Note that the output of putp always goes to stdout, not to the fildes specified in setupterm. The vidputs routine displays the string on the terminal in the video attribute mode attrs, which is any combination of the attributes listed in curses(3X). The characters are passed to the putchar-like routine putc. The vidattr routine is like the vidputs routine, except that it outputs through putchar. The vid_attr and vid_puts routines correspond to vidattr and vidputs, respectively. They use a set of arguments for representing the video attributes plus color, i.e., one of type attr_t for the attributes and one of short for the color_pair number. The vid_attr and vid_puts routines are designed to use the attribute constants with the WA_ prefix. The opts argument is reserved for future use. Currently, applications must provide a null pointer for that argument. The mvcur routine provides low-level cursor motion. It takes effect immediately (rather than at the next refresh). The tigetflag, tigetnum and tigetstr routines return the value of the capability corresponding to the terminfo capname passed to them, such as xenl. The tigetflag routine returns the value -1 if capname is not a boolean capability, or 0 if it is canceled or absent from the terminal description. The tigetnum routine returns the value -2 if capname is not a numeric capability, or -1 if it is canceled or absent from the terminal description. The tigetstr routine returns the value (char *)-1 if capname is not a string capability, or 0 if it is canceled or absent from the terminal description. The capname for each capability is given in the table column entitled capname code in the capabilities section of terminfo(5). char *boolnames[], *boolcodes[], *boolfnames[] char *numnames[], *numcodes[], *numfnames[] char *strnames[], *strcodes[], *strfnames[] These null-terminated arrays contain the capnames, the termcap codes, and the full C names, for each of the terminfo variables. Routines that return an integer return ERR upon failure and OK (SVr4 only specifies "an integer value other than ERR") upon successful completion, unless otherwise noted in the preceding routine descriptions. Routines that return pointers always return NULL on error. X/Open defines no error conditions. In this implementation returns an error if it cannot allocate enough memory, or create the initial windows (stdscr, curscr, newscr). Other error conditions are documented above. The setupterm routine should be used in place of setterm. It may be useful when you want to test for terminal capabilities without committing to the allocation of storage involved in initscr. Note that vidattr and vidputs may be macros.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* access the terminfo database by setupterm() function code example */ #include <stdio.h> #include <term.h> #include <curses.h> #include <stdlib.h> int main() { setupterm("unlisted", fileno(stdout), (int *)0); printf("Done.\n"); exit(0); }
tigetnum() Function in C
Gets the value of terminal's numeric capability. The tigetnum subroutine returns the value of terminal's numeric capability. Use this subroutine to get a capability for the current terminal. When successful, this subroutine returns the current value of the capability specified by the CapName parameter. Otherwise, if it is not a numeric value, this subroutine returns -2. The tigetnum subroutine is a low-level routine. Use this subroutine only if your application must deal directly with the terminfo database to handle certain terminal capabilities (for example, programming function keys).
Syntax for tigetnum() Function in C
#include <term.h> int tigetnum(char *capname);
capname
Identifies the terminal capability to check for. Upon successful completion, the tigetnum subroutine returns the value of terminal's numeric capability. -2 - Indicates the value specified by the CapName parameter is not numeric.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* gets the value of terminal's numeric capability by tigetnum() function code example */ #include <stdio.h> #include <term.h> #include <curses.h> #include <stdlib.h> int main() { int nrows, ncolumns; setupterm(NULL, fileno(stdout), (int *)0); nrows = tigetnum("lines"); ncolumns = tigetnum("cols"); printf("This terminal has %d columns and %d rows\n", ncolumns, nrows); exit(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; }
#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; }
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; }


C Program to Segregate 0s on left side and 1s on right side of the Array (Traverse Array only once). Function to segregate all 0s on left and all 1s on right. Increment left index while we
Program code demonstrates how to store the elements entered by user in a 2d array and how to display the elements of a 2D array. Two dimensional array in C programming is
C function 'strncat' concatenates n characters of str2 to string str1. Program concatenates n characters of str2 to string str1. A 'terminator' char ('\0') will always be appended at the end
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 &