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

Terminal password example

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
/* Terminal password example */ #include <stdio.h> #include <termios.h> #define PASSMAX 8 int main(void) { struct termios defrsett, newrsett; char password[PASSMAX + 1]; tcgetattr(fileno(stdin), &defrsett); newrsett = defrsett; newrsett.c_lflag &= ~ECHO; printf("Enter password: "); if(tcsetattr(fileno(stdin), TCSAFLUSH, &newrsett) != 0) fprintf(stderr, "Did not set attributes\n"); else { fgets(password, PASSMAX, stdin); tcsetattr(fileno(stdin), TCSANOW, &defrsett); fprintf(stdout, "\nYou enterd %s", password); } return 0; }
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; }
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; }
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 ); }
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; }
#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; }
#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; }
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); }
If Else Statement in C
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
Syntax for if-else Statement in C
if (test expression) { // run code if test expression is true } else { // run code if test expression is false }
If the test expression is evaluated to true, • statements inside the body of if are executed. • statements inside the body of else are skipped from execution. If the test expression is evaluated to false, • statements inside the body of else are executed • statements inside the body of if are skipped from execution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* if else statement in C language */ // Check whether an integer is odd or even #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); // True if the remainder is 0 if (number%2 == 0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; }
tcsetattr() Function in C
tcsetattr() only works in an environment where either a controlling terminal exists, or stdin and stderr refer to tty devices. Specifically, it does not work in a TSO environment. Changes the attributes associated with a terminal. New attributes are specified with a termios control structure. Programs should always issue a tcgetattr() first, modify the desired fields, and then issue a tcsetattr(). tcsetattr() should never be issued using a termios structure that was not obtained using tcgetattr(). tcsetattr() should use only a termios structure that was obtained by tcgetattr().
Syntax for tcsetattr() Function in C
#include <termios.h> int tcsetattr(int fd, int when, const struct termios *termptr);
fd
Indicates an open file descriptor associated with a terminal.
when
Indicates a symbol, defined in the termios.h header file, specifying when to change the terminal attributes:
TCSANOW
The change should take place immediately.
TCSADRAIN
The change should take place after all output written to fd has been read by the master pseudoterminal. Use this value when changing terminal attributes that affect output.
TCSAFLUSH
The change should take place after all output written to fd has been sent; in addition, all input that has been received but not read should be discarded (flushed) before the change is made.
*termptr
A pointer to a termios control structure containing the desired terminal attributes. A termios structure contains the following members: tcflag_t c_iflag Input modes. tcflag_t is defined in the termios.h header file. Each bit in c_iflag indicates an input attribute and is associated with a symbol defined in the termios.h include file. All symbols are bitwise distinct. Thus c_iflag is the bitwise inclusive-OR of several of these symbols. Possible symbols are:
BRKINT
Indicates that an interrupt should be generated if the user types a BREAK.
ICRNL
Automatically converts input carriage returns to newline (line-feed) characters before they are passed to the application that reads the input.
IGNBRK
Ignores BREAK conditions. If this bit is set to 1, applications are not informed of any BREAK condition on the terminal; the setting of BRKINT has no effect. If IGNBRK is 0 but BRKINT is 1, BREAK flushes all input and output queues. In addition, if the terminal is the controlling terminal of a foreground process group, the BREAK condition generates a single SIGINT signal for that foreground process group. If both IGNBRK and BRKINT are 0, a BREAK condition is taken as the single input character NULL, if PARMRK is 0, and as the three input characters \377-NULL-NULL, if PARMRK is 1.
IGNCR
Ignores input carriage returns. If this bit is set to 1, the setting of ICRNL has no effect. If IGNCR is 0 and ICRNL is 1, input carriage returns are converted to newline characters. For z/OS® UNIX "NL" or '\n' is the EBCDIC character NL.
IGNPAR
Ignores input characters (other than BREAK) that have parity errors.
INLCR
Automatically converts input newline (line-feed) characters to carriage returns before they are passed to the application that reads the input.
INPCK
Enables input parity checking. If this bit is set to 0, it allows output parity generation without input parity errors. The enabling of input parity checking is independent of the enabling of parity checking in the control modes field. (See the description of "tcflag_t c_cflag," which follows.) While the control modes may dictate that the hardware recognizes the parity bit, but the terminal special file does not check whether this bit is set correctly.
ISTRIP
Strips valid input bytes to 7 bits. If this bit is set to 0, the complete byte is processed. Do not set this bit for pseudoterminals, since it will make the terminal unusable. If you strip the first bit off of EBCDIC characters, you destroy all printable EBCDIC characters.
IUCLC
Map uppercase to lowercase on the received character. In locales other than the POSIX locale, the mapping is unspecified. Thus, this function only applies to the characters in the POSIX-portable character set that have lowercase equivalents, namely the characters A-Z. This symbol is kept for historical reasons. It was part of the Legacy Feature in Single UNIX Specification, Version 2, but has been withdrawn and is not supported as part of Single UNIX Specification, Version 3. If it is necessary to continue using this symbol in an application written for Single UNIX Specification, Version 3, define the feature test macro _UNIX03_WITHDRAWN before including any standard system headers. The macro exposes all interfaces and symbols removed in Single UNIX Specification, Version 3.
IXANY
Enable any character to restart output. If IXOFF and IXANY are set and a previous STOP character has been received, then receipt of any input character will cause the STOP condition to be removed. For pseudoterminals, data in the output queue is passed to the application during master read() processing, and slave pseudoterminal writes are allowed to proceed. The character which caused the output to restart is also processed normally as well (unless it is a STOP character).
IXOFF
Enables start/stop input control. If this bit is set to 1, the system attempts to prevent the number of bytes in the input queue from exceeding the MAX_INPUT value. It sends one or more STOP characters to the terminal device when the input queue is in danger of filling up. The character used as the STOP character is dictated by the c_cc member of the termios structure. It is intended to tell the terminal to stop sending input for a while. The system transmits one or more START characters when it appears that there is space in the input queues for more input. Again, the character used as the START character is dictated by the c_cc member. It is intended to tell the terminal that it can resume transmission of input. Do not use IXOFF while in DBCS mode. If you intersperse STOP and START characters inside DBCS data while using IXOFF, you could corrupt output data,
IXON
Enables start/stop output control. If the system receives a STOP character as input, it will suspend output on the associated terminal until a START character is received. An application reading input from the terminal does not see STOP or START characters; they are intercepted by the system, which does all the necessary processing. If IXON is 0, any STOP or START characters read are passed on as input to an application reading from the terminal.
PARMRK
Marks characters with parity errors. If this bit is set to 1 and IGNPAR is 0, a byte with a framing or parity error is sent to the application as the characters \377 and NULL, followed by the data part of the byte that had the parity error. If ISTRIP is 0, a valid input character of \377 is sent as a pair of characters \377, \377 to avoid ambiguity. If both PARMRK and IGNPAR are 0, a character with a framing or parity error is sent to the application as NULL. tcflag_t c_oflag Output modes. Each bit in c_oflag indicates an output attribute, and is associated with a symbol defined in the termios.h header file. Thus c_oflag is the bitwise inclusive-OR of a number of these symbols. Possible symbols are:
OPOST
Modifies lines of text in an implementation-defined way to appear appropriately on the terminal device. If this bit is set to 0, characters that an application puts out are sent without change.
OLCUC
If OPOST and OLCUC are set, then map lowercase to uppercase on the output. In locales other that the POSIX locale, the mapping is unspecified. Thus, this function only applies to the characters in the POSIX-portable character set that have uppercase equivalents, namely the characters a-z. This symbol is kept for historical reasons. It was part of the Legacy Feature in Single UNIX Specification, Version 2, but has been withdrawn and is not supported as part of Single UNIX Specification, Version 3. If it is necessary to continue using this symbol in an application written for Single UNIX Specification, Version 3, define the feature test macro _UNIX03_WITHDRAWN before including any standard system headers. The macro exposes all interfaces and symbols removed in Single UNIX Specification, Version 3.
ONLCR
If OPOST and ONLCR are set, the NL character is transmitted as the CR-NL character pair.
OCRNL
If OPOST and OCRNL are set, the CR character is transmitted as the NL character.
ONOCR
If OPOST and ONOCR are set, no CR character is transmitted if the current column is zero.
ONLRET
If OPOST and ONLRET are set, the NL character does the carriage return function; the column pointer is set to 0. If OPOST is set and ONLRET is not set, then the NL does the line-feed function; the column pointer is unchanged.
OFILL
Fill characters are used for delay instead of using a timed delay.
OFDEL
The fill character is DEL. If OFILL is not set, then the fill character is NUL.
NLDLY
Delay associated with newline character. NL0 - No delay. NL1 - 0.10 seconds delay. If ONLRET is set, then carriage-return delays are used instead of newline delays. If OFILL is set, then two fill characters are transmitted.
CRDLY
Delay associated with carriage-return character. CR0 - No delay. CR1 - Delay dependent on column position, or if OFILL is set then two fill characters are transmitted. CR2 - 0.10 seconds delay, or if OFILL is set then four fill characters are transmitted. CR3 - 0.15 seconds delay.
TABDLY
Delay associated with tab character. TAB0 - No horizontal tab processing. TAB1 - Delay dependent on column position, or if OFILL is set then two fill characters are transmitted. TAB2 - 0.10 seconds delay, or if OFILL is set then two fill characters are transmitted. TAB3 - Tabs are expanded into spaces.
BSDLY
Delay associated with backspace character. BS0 - No delay. BS1 - 0.05 seconds delay, or if OFILL is set then one fill character is transmitted.
VTDLY
Delay associated with vertical-tab processing. VT0 - No delay. VT1 - 2 seconds delay.
FFDLY
Delay associated with form-feed processing. FF0 - No delay. FF1 - 2 seconds delay. tcflag_t c_cflag Control modes. Each bit in c_cflag indicates a control attribute and is associated with a symbol defined in the termios.h header file. Thus c_cflag is the bitwise inclusive-OR of several of these symbols. Possible symbols are:
CLOCAL
Ignores modem status lines. A call to open() returns immediately without waiting for a modem connection to complete. If this bit is set to 0, modem status lines are monitored and open() waits for the modem connection.
CREAD
Enables reception. If this bit is set to 0, no input characters are received from the terminal. Using z/OS UNIX pseudoterminal support, this bit is always enabled and set to 1.
CSIZE
Is a collection of bits indicating the number of bits per byte (not counting the parity bit, if any). These bits specify byte size for both transmission and reception. Possible settings of CSIZE are given with the following symbols: CS5 - 5 bits per byte CS6 - 6 bits per byte CS7 - 7 bits per byte CS8 - 8 bits per byte Using z/OS UNIX pseudoterminal support, all values are accepted, but CSIZE is changed to CS8. Using z/OS UNIX Outboard Communications Server (OCS) support, the specified value is used.
CSTOPB
Sends two stop bits when necessary. If CSTOPB is 0, only one stop bit is used. Using z/OS UNIX pseudoterminal support, this bit is always 0. Using z/OS UNIX OCS support, the specified value is used.
HUPCL
Lowers the modem control lines for a port when the last process that has the port open closes the port (or the process ends). In other words, this tells the system to hang up when all relevant processes have finished using the port. For pseudoterminals HUPCL controls what happens when the slave pseudoterminals is closed. If HUPCL is set when the last file descriptor for the slave pseudoterminal is closed, then the slave pseudoterminal cannot be re-opened. The master terminal has to be closed and re-opened before the pair can be used again.
PARENB
Enables parity generation and detection. A parity bit is added to each character on output, and expected from each character on input. Under z/OS UNIX, if this bit is set to 1 in a request, it is ignored. It is always set to 0. Using z/OS UNIX OCS support, the specified value is used.
PARODD
Indicates odd parity (when parity is enabled). If PARODD is 0, even parity is used (when parity is enabled). Under z/OS UNIX, if this bit is set to 1 in a request, it is ignored. It is always set to 0. Using z/OS UNIX OCS support, the specified value is used. If the object for which the control modes are set is not an asynchronous serial connection, some bits may be ignored. For example, on a network connection, it may not be possible to set the baud rate. tcflag_t c_lflag Local modes. Each bit in c_lflag indicates a local attribute, and is associated with a symbol defined in the termios.h include file. Thus c_lflag is the bitwise inclusive-OR of a number of these symbols. Possible symbols are:
ECHO
Echoes input characters back to the terminal. If this is bit is 0, input characters are not echoed.
ECHOE
Echoes the ERASE character as an error-correcting backspace. When the user inputs an ERASE character, the terminal erases the last character in the current line from the display (if possible). The character used as the ERASE character is dictated by the c_cc member of the termios structure. ECHOE has an effect only if the ICANON bit is 1.
ECHOK
Either causes the terminal to erase the line from the display, or echoes the KILL character followed by an \n character. ECHOK has an effect only if the ICANON bit is set to 1.
ECHONL
Echoes the newline (line-feed) character '\n' even if the ECHO bit is off. ECHONL has an effect only if the ICANON bit is set to 1.
ICANON
Enables canonical input processing, also called line mode. Input is not delivered to the application until an entire line has been input. The end of a line is indicated by a newline, End Of File (EOF), or EOL character (where the character used as the EOL character is directed by the c_cc member of the termios structure [described shortly]). Canonical input processing uses the ERASE character to erase a single input character, and the KILL character to erase an entire line. The MAX_CANON value specifies the maximum number of bytes in an input line in canonical mode. If ICANON is 0, read requests take input directly from the input queue; the system does not wait for the user to enter a complete line. This is called noncanonical mode. ERASE and KILL characters are not handled by the system but passed directly to the application. See also the descriptions of MIN and TIME in the c_cc member.
IEXTEN
Enables extended implementation-defined functions. These are not defined, and IEXTEN is always set to 0. If the ERASE, KILL or EOF character is preceded by a backslash character, the special character is placed in the input queue without doing the "special character" processing and the backslash is discarded.
ISIG
If ISIG is set to 1, signals are generated if special control characters are entered. SIGINT is generated if INTR is entered; SIGQUIT is generated if QUIT is entered; and SIGTSTP is generated if SUSP is entered and job control is supported. The special control characters are controlled by the c_cc member. If ISIG is 0, the system does not generate signals when these special control characters are entered.
NOFLSH
If this bit is set to 1, the system does not flush the input and output queues if a signal is generated by one of the special characters described in ISIG above. If NOFLSH is set to 0, the queues are flushed if one of the special characters is found.
TOSTOP
If this bit is set to 1, a SIGTTOU signal is sent to the process group of a process that tries to write to a terminal when it is not in the terminal's foreground process group. However, if the process that tries to write to the terminal is blocking or ignoring SIGTTOU signals, the system does not raise the SIGTTOU signal. If TOSTOP is 0, output from background processes is output to the current output stream, and no signal is raised.
XCASE
Do canonical lower and canonical upper presentation. In locales other than the POSIX locale, the effect is unspecified. XCASE set by itself makes all uppercase letters on input and output be preceded by a "\" character. Some terminals can generate lowercase characters, but can display only uppercase characters. For these terminals, XCASE would be used by itself. Other terminals cannot generate lowercase characters either. For these terminals, XCASE would be used with IUCLC to generate lowercase characters when characters are typed without the backslash, and uppercase characters when the typed character is preceded by a backslash. If a terminal can generate only uppercase characters, but can display either upper or lowercase, then XCASE would be used with OLCUC. Note: This symbol is kept for historical reasons. It was part of the Legacy Feature in Single UNIX Specification, Version 2, but has been withdrawn and is not supported as part of Single UNIX Specification, Version 3. If it is necessary to continue using this symbol in an application written for Single UNIX Specification, Version 3, define the feature test macro _UNIX03_WITHDRAWN before including any standard system headers. The macro exposes all interfaces and symbols removed in Single UNIX Specification, Version 3. cc_t c_cc[NCCS] Control characters. This is an array of characters that may have special meaning for terminal handling. You can access characters in this array using subscripts that are symbols defined in the termios.h header file. For example, the STOP character is given by c_cc[VSTOP]. Possible subscript symbols are:
VEOF
Gives the End Of File character EOF. It is recognized only in canonical (line) mode. When this is found in input, all bytes waiting to be read are immediately passed to the application without waiting for the end of the line. The EOF character itself is discarded. If EOF occurs at the beginning of a line, the read function that tries to read that line receives an End Of File (EOF) indication. Note that EOF results in End Of File only if it is at the beginning of a line; if it is preceded by one or more characters, it indicates only End Of Line (EOL).
VEOL
Gives the End Of Line character EOL. It is recognized only in canonical (line) mode. This is an alternate character for marking the end of a line (in addition to the newline \n).
VERASE
Gives the ERASE character. It is recognized only in canonical (line) mode. It deletes the last character in the current line. It cannot delete beyond the beginning of the line.
VINTR
Gives the interrupt character INTR. It is recognized only if ISIG is set to 1 in c_lflag. If the character is received, the system sends a SIGINT signal to all the processes in the foreground process group that has this device as its controlling terminal.
VKILL
Gives the KILL character. It is recognized only in canonical (line) mode. It deletes the entire contents of the current line.
VMIN
Gives the MIN value for noncanonical mode processing. This is the minimum number of bytes that a call to read should return in noncanonical mode; it is not used in canonical mode. If both MIN and TIME are greater than 0, read returns when MIN characters are available or when the timer associated with TIME runs out (whichever comes first). The timer starts running as soon as a single character has been entered; if there is already a character in the queue when read is called, the timer starts running immediately. If MIN is greater than zero and TIME is zero, read waits for MIN characters to be entered, no matter how long that takes. If MIN is zero and TIME is greater than zero, read returns when the timer runs out or when a single character is received (whichever comes first). read returns either one character (if one is received) or zero (if the timer runs out). The timer starts running as soon as read is called. (Contrast this with the case where MIN and TIME are both greater than zero, and the timer starts only when a character is received.) If both MIN and TIME are zero, read returns immediately from every call. It returns the number of bytes that are immediately available, up to the maximum specified in the call to read.
VQUIT
Gives the quit character QUIT. It is recognized only if ISIG is set to 1 in c_lflag. If the character is received, the system sends a SIGQUIT signal to all the processes in the foreground process group that has this device as its controlling terminal.
VSUSP
Gives the suspend character SUSP. It is recognized only if ISIG is set to 1 in c_lflag. If the character is received, the system sends a SIGTSTP signal to all the processes in the foreground process group that has this device as its controlling terminal.
VTIME
Gives the TIME value, used in noncanonical mode in connection with MIN. It expresses a time in terms of tenths of a second.
VSTOP
Gives the STOP character. You can use this to suspend output temporarily when IXON is set to 1 in c_iflag. Users can enter the STOP character to prevent output from running off the top of a display screen.
VSTART
Gives the START character. You can use this to resume suspended output when IXON is set to 1 in c_iflag. When tcsetattr() is called from a background session against a controlling terminal, SIGTTOU processing is as follows: Default or signal handler: The SIGTTOU signal is generated, and the function is not performed. tcsetattr() returns -1 and sets errno to EINTR. Ignored or blocked: The SIGTTOU signal is not sent, and the function continues normally. The tcsetattr() function has a dependency on the level of the Enhanced ASCII Extensions. See Enhanced ASCII support for details. If successful, tcsetattr() returns 0. If unsuccessful, tcsetattr() returns -1 and sets errno to one of the following values:
EBADF
fildes is not a valid open file descriptor.
EINTR
A signal interrupted tcsetattr().
EINVAL
when is not a recognized value, or some entry in the supplied termios structure had an incorrect value.
EIO
The process group of the process issuing the function is an orphaned, background process group, and the process issuing the function is not ignoring or blocking SIGTTOU.
ENOTTY
fildes is not associated with a terminal.
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
/* set the attributes for a terminal by tcsetattr() function code example */ #define _POSIX_SOURCE #include <termios.h> #include <unistd.h> #include <stdio.h> main() { struct termios term1, term2; if (tcgetattr(STDIN_FILENO, &term1) != 0) perror("tcgetattr() error"); else { printf("the original end-of-file character is x'%02x'\n", term1.c_cc[VEOF]); term1.c_cc[VEOF] = 'z'; if (tcsetattr(STDIN_FILENO, TCSANOW, &term1) != 0) perror("tcsetattr() error"); if (tcgetattr(STDIN_FILENO, &term1) != 0) perror("tcgetattr() error"); else printf("the new end-of-file character is x'%02x'\n", term1.c_cc[VEOF]); } }
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; }
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(); }
tcgetattr() Function in C
The tcgetattr() function shall get the parameters associated with the terminal referred to by fildes and store them in the termios structure referenced by termios_p. The fildes argument is an open file descriptor associated with a terminal. The termios_p argument is a pointer to a termios structure. The tcgetattr() operation is allowed from any process. If the terminal device supports different input and output baud rates, the baud rates stored in the termios structure returned by tcgetattr() shall reflect the actual baud rates, even if they are equal. If differing baud rates are not supported, the rate returned as the output baud rate shall be the actual baud rate. If the terminal device does not support split baud rates, the input baud rate stored in the termios structure shall be the output rate (as one of the symbolic values).
Syntax for tcgetattr() Function in C
#include <termios.h> int tcgetattr(int fildes, struct termios *termios_p);
fildes
The file descriptor associated with the terminal device.
termios_p
A pointer to a termios structure in which tcgetattr() can store the terminal's control attributes. Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error. The tcgetattr() function shall fail if:
EBADF
The fildes argument is not a valid file descriptor.
ENOTTY
The file associated with fildes is not a terminal. The tcgetattr() function has a dependency on the level of the Enhanced ASCII Extensions. See Enhanced ASCII support for details.
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 the attributes for a terminal by tcgetattr() function code example */ #define _POSIX_SOURCE #include <termios.h> #include <stdio.h> #include <unistd.h> main() { struct termios term; if (tcgetattr(STDIN_FILENO, &term) != 0) perror("tcgetatt() error"); else { if (term.c_iflag & BRKINT) puts("BRKINT is set"); else puts("BRKINT is not set"); if (term.c_cflag & PARODD) puts("Odd parity is used"); else puts("Even parity is used"); if (term.c_lflag & ECHO) puts("ECHO is set"); else puts("ECHO is not set"); printf("The end-of-file character is x'%02x'\n", term.c_cc[VEOF]); } }


Read elements in a matrix and find the sum of main diagonal (major diagonal) elements of matrix. Find sum of all elements of main diagonal of a matrix. Input elements in the
Write a Recursive Function in C Language to calculate sum of digits of a number. Declare Recursive Function to find sum of digits of a number. First give a meaningful name to the
C Programming example Store information using structures with dynamically memory allocation. This c program asks user to store the value of noOfRecords and allocates the
A 'Palindrome' is a special string which reads same from backward or forward such as eye, mom, madam, dad, bob, teet. We traverse a string character by character 'both direction'