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

Userinfo on x os from C

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
/* Userinfo on x os from C */ #include <pwd.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(void) { uid_t uid; gid_t gid; struct passwd *pw; uid = getuid(); gid = getgid(); printf("I am user: %s\n", getlogin()); printf(" uid: %d\n", uid); printf(" gid: %d\n", gid); printf("\n"); pw = getpwuid(uid); printf("Password entry for user %s:\n", pw->pw_name); printf(" name : %s\n", pw->pw_name); printf(" uid : %d\n", pw->pw_uid); printf(" gid : %d\n", pw->pw_gid); printf(" home : %s\n", pw->pw_dir); printf(" shell: %s\n", pw->pw_shell); printf("\n"); printf("Password entry for root:\n"); pw = getpwnam("root"); printf(" name : %s\n", pw->pw_name); printf(" uid : %d\n", pw->pw_uid); printf(" gid : %d\n", pw->pw_gid); printf(" home : %s\n", pw->pw_dir); printf(" shell: %s\n", pw->pw_shell); return 0; }
getlogin() Function in C
Finds the name that the login process associated with the current terminal. This string is stored in a static data area and, therefore, may be overwritten with every call to getlogin(). Special behavior for _POSIX_SOURCE: If called from a batch program, a TSO command, or a shell command, getlogin() returns the MVS™ user name associated with the program. With z/OS® UNIX services, this name is a TSO/E user ID. When _POSIX_SOURCE is defined and _XOPEN_SOURCE is not defined, then getlogin() is the same as __getlogin1().
Syntax for getlogin() Function in C
#include <unistd.h> char *getlogin(void);
Special behavior for XPG4.2: You must have a TTY at file descriptor 0, 1, or 2, and the TTY must be recorded in the /etc/utmpx database. Someone must have logged in using the TTY. Also, the program must be invoked from a shell session, and file descriptors 0, 1, and 2 are not all redirected. If getlogin() cannot determine the login name, you can call getuid() to get the user ID of the process, and then call getpwuid() to get a login name associated with that user ID. getpwuid() always returns the passwd struct for the same user, even if multiple users have the same UID. If successful, getlogin() returns a pointer to a string that has the login name for the current terminal. Special behavior for _POSIX_SOURCE: If unsuccessful, getlogin() returns the NULL pointer. There are no documented errno values. Special behavior for XPG4.2: If unsuccessful, getlogin() returns a NULL pointer and sets errno to one of the following values:
EMFILE
OPEN_MAX file descriptors are currently open in the calling process.
ENFILE
The maximum allowable number of files is currently open in the system.
ENXIO
The calling process has no controlling terminal.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* get the user login name by getlogin() function code example */ /* This example gets the user login name. */ #define _POSIX_SOURCE #include <stdio.h> #include <unistd.h> main() { char *user; if ((user = __getlogin1()) == NULL) perror("__getlogin1() error"); else printf("__getlogin1() returned %s\n", user); }
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; }
getpwnam() Function in C
Get information about the user with a given name. The getpwnam() function shall search the user database for an entry with a matching name. The getpwnam() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe. Applications wishing to check for error situations should set errno to 0 before calling getpwnam(). If getpwnam() returns a null pointer and errno is non-zero, an error occurred. The getpwnam() function returns a pointer to a structure containing the broken-out fields of the record in the password database (e.g., the local password file /etc/passwd, NIS, and LDAP) that matches the username name.
Syntax for getpwnam() Function in C
#include <pwd.h> struct passwd *getpwnam(const char *name);
name
The name of the user whose entry you want to find. Accesses the passwd structure (defined in the pwd.h header file), which contains the following members: • pw_name - User name. • pw_uid - User ID (UID) number. • pw_gid - Group ID (GID) number. • pw_dir - Initial working directory. • pw_shell - Initial user program. If successful, getpwnam() returns a pointer to a passwd structure containing an entry from the user database with the specified name. Return values may point to the static data that is overwritten on each call. If unsuccessful, getpwnam() returns a NULL pointer and sets errno to one of the following values: EINVAL - A non-valid user name is detected.
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
/* get information about the user with a given name by getpwnam() function code example */ /* Print information from the password entry about the user name given as argv[1]. */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <pwd.h> int main( int argc, char* *argv ) { struct passwd* pw; if( ( pw = getpwnam( argv[1] ) ) == NULL ) { fprintf( stderr, "getpwnam: unknown %s\n", argv[1] ); return( EXIT_FAILURE ); } printf( "login name %s\n", pw->pw_name ); printf( "user id %d\n", pw->pw_uid ); printf( "group id %d\n", pw->pw_gid ); printf( "home dir %s\n", pw->pw_dir ); printf( "login shell %s\n", pw->pw_shell ); return( EXIT_SUCCESS ); }
#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; }
getuid() Function in C
Get the real user ID. Finds the real user ID (UID) of the calling process. The getuid() system call returns the real user ID of the calling process. The geteuid() system call returns the effective user ID of the calling process. The real user ID is that of the user who has invoked the program. As the effective user ID gives the process additional permissions during execution of "set-user-ID" mode processes, getuid() is used to determine the real-user-id of the calling process.
Syntax for getuid() Function in C
#include <unistd.h> uid_t getuid(void);
The getuid() and geteuid() system calls are always successful, and no return value is reserved to indicate an error. The geteuid() and getuid() system calls are expected to conform to ISO/IEC 9945-1:1990 ("POSIX.1").
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* get the real user ID of the calling process by getuid() function code example */ /* This example provides information for your user ID. */ #define _POSIX_SOURCE #include <pwd.h> #include <sys/types.h> #include <unistd.h> main() { struct passwd *p; uid_t uid; if ((p = getpwuid(uid = getuid())) == NULL) perror("getpwuid() error"); else { puts("getpwuid() returned the following info for your userid:"); printf(" pw_name : %s\n", p->pw_name); printf(" pw_uid : %d\n", (int) p->pw_uid); printf(" pw_gid : %d\n", (int) p->pw_gid); printf(" pw_dir : %s\n", p->pw_dir); printf(" pw_shell : %s\n", p->pw_shell); } }
getpwuid() Function in C
The getpwuid() function shall search the user database for an entry with a matching uid. The getpwuid() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe. Applications wishing to check for error situations should set errno to 0 before calling getpwuid(). If getpwuid() returns a null pointer and errno is set to non-zero, an error occurred. Access the user database by user ID. Gets information about a user with the specified uid. getpwuid() returns a pointer to a passwd structure containing an entry from the user database for the specified uid.
Syntax for getpwuid() Function in C
#include <pwd.h> struct passwd *getpwuid(uid_t uid);
uid
The userid whose entry you want to find. This structure (defined in the pwd.h header file), contains the following members: • pw_name - User name. • pw_uid - User ID (UID) number. • pw_gid - Group ID (GID) number. • pw_dir - Initial working directory. • pw_shell - Initial user program. Return values may point to the static data that is overwritten on each call. If successful, getpwuid() returns a pointer. If unsuccessful, getpwuid() returns a NULL pointer and sets errno to one of the following values: EMVSSAF2ERR - The system authorization facility (SAF) or RACF Get GMAP or Get UMAP service had an error. EMVSSAFEXTRERR - The SAF or RACF RACROUTE EXTRACT service had an error. The getpwent(), getpwnam(), and getpwuid() functions share the same static buffer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/* get information about the user with a given ID by getpwuid() function code example */ /* Print password info on the current user. */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <pwd.h> int main( void ) { struct passwd* pw; if( ( pw = getpwuid( getuid() ) ) == NULL ) { fprintf( stderr, "getpwuid: no password entry\n" ); return( EXIT_FAILURE ); } printf( "login name %s\n", pw->pw_name ); printf( "user id %d\n", pw->pw_uid ); printf( "group id %d\n", pw->pw_gid ); printf( "home dir %s\n", pw->pw_dir ); printf( "login shell %s\n", pw->pw_shell ); return( EXIT_SUCCESS ); }
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; }


Insert, swap, search value, search minimum and search maximum values. Destroy, count tree nodes. Insert a tnode into the binary tree. Traverse the tree to get a pointer to the
Takes the binary number (entered by user) as input and converts it into a decimal number using function. To understand this program, you should be familiar with the following C...
First give a meaningful name to the recursive function to print even odd numbers. Let's say printEvenOdd(). This function can print both even as well as Odd Numbers in given range.
Before accepting the Elements Check if no of rows and columns of both matrices is equal. Accept the Elements in Matrix 1 and Matrix 2. Addition of two matrices. Print out the matrix
This program takes a string as input and print the words ending with letter "s". Take a string as input and store it in the array str[]. Find its length & add a blank space to the input string
Choose a two digit number and add digits. Subtract the sum from original number. See the symbol opposit to the number you got. Press any key The MIND READER will display