C Programming Code Examples
C > C on Unix Code Examples
Program to work on Child Processes
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
/* Program to work on Child Processes */
# include < stdio.h>
# include < stdlib.h>
# include < unistd.h>
int main()
{
long limit;
/* GET THE LIMIT OF THE ARGUMENT */
if((limit = sysconf(_SC_ARG_MAX)) < 0)
{
perror("ARG MAXIMUM LIMIT ERROR
");
}
else
{
printf("ARGUMENT LIMIT IS %ld
",limit);
}
/* GET THE LIMIT OF THE CHILD PROCESS */
if((limit = sysconf(_SC_CHILD_MAX)) < 0)
{
perror("CHILD MAXIMUM LIMIT ERROR
");
}
else
{
printf("MAXIMUM CHILD PROCESS %ld
",limit);
}
printf("
");
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;
}
perror() Function in C
Print error message. Interprets the value of errno as an error message, and prints it to stderr (the standard error output stream, usually the console), optionally preceding it with the custom message specified in str.
errno is an integral variable whose value describes the error condition or diagnostic information produced by a call to a library function (any function of the C standard library may set a value for errno, even if not explicitly specified in this reference, and even if no error happened), see errno for more info.
Syntax for perror() Function in C
#include <stdio.h>
void perror ( const char * str );
str
C string containing a custom message to be printed before the error message itself. If it is a null pointer, no preceding custom message is printed, but the error message is still printed. By convention, the name of the application itself is generally used as parameter.
This function does not return any value.
The error message produced by perror is platform-depend.
If the parameter str is not a null pointer, str is printed followed by a colon (:) and a space. Then, whether str was a null pointer or not, the generated error description is printed followed by a newline character ('\n').
perror should be called right after the error was produced, otherwise it can be overwritten by calls to other functions.
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
/* print an error message corresponding to the value of errno with perror() function code example */
/* error handling with perror() function and errno */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
main()
{
FILE *fp;
char filename[80];
printf("Enter filename: ");
gets(filename);
if (( fp = fopen(filename, "r")) == NULL)
{
perror("You goofed!");
printf("errno = %d.\n", errno);
exit(1);
}
else
{
puts("File opened for reading.");
fclose(fp);
}
return(0);
}
printf() Function in C
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.
printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers, but are sufficient for many purposes.
Syntax for printf() function in C
#include <stdio.h>
int printf ( const char * format, ... );
format
C string that contains the text to be written to stdout.
It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested.
A format specifier follows this prototype: [see compatibility note below]
%[flags][width][.precision][length]specifier
Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
specifier
a conversion format specifier.
d or i
Signed decimal integer
u
Unsigned decimal integer
o
Unsigned octal
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer (uppercase)
f
Decimal floating point, lowercase
F
Decimal floating point, uppercase
e
Scientific notation (mantissa/exponent), lowercase
E
Scientific notation (mantissa/exponent), uppercase
g
Use the shortest representation: %e or %f
G
Use the shortest representation: %E or %F
a
Hexadecimal floating point, lowercase
A
Hexadecimal floating point, uppercase
c
Character
s
String of characters
p
Pointer address
n
Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location.
%
A % followed by another % character will write a single % to the stream.
The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
flags
one or more flags that modifies the conversion behavior (optional)
-
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
+
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
(space)
If no sign is going to be written, a blank space is inserted before the value.
#
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
0
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
width
an optional * or integer value used to specify minimum width field.
(number)
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
*
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
.precision
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
.number
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
For g and G specifiers: This is the maximum number of significant digits to be printed.
For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
If the period is specified without an explicit value for precision, 0 is assumed.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
length
an optional length modifier that specifies the size of the argument.
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.
If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.
If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* print formatted data to stdout by printf() function example */
#include <stdio.h>
int main()
{
char ch;
char str[100];
int a;
float b;
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
printf("Enter integer and then a float: ");
// Taking multiple inputs
scanf("%d%f", &a, &b);
printf("You entered %d and %f", a, b);
return 0;
}
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
}
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;
}
sysconf() Function in C
Determine system configuration options. The sysconf() function provides a method for the application to determine the current value of a configurable system limit or option ( variable). The implementation shall support all of the variables listed in the following table and may support others.
The name argument represents the system variable to be queried. The following table lists the minimal set of system variables from <limits.h> or <unistd.h> that can be returned by sysconf(), and the symbolic constants defined in <unistd.h> that are the corresponding values used for name.
Syntax for sysconf() Function in C
#include <unistd.h>
long sysconf(int name);
name
Specifies the system configuration option to be obtained. The value of name can be any one of the following set of symbols defined in the unistd.h header file, each corresponding to a system configuration option:
The following are available when _POSIX_SOURCE is defined.
_SC_ARG_MAX
Represents ARG_MAX, as defined by the values returned by sysconf(), the maximum number of bytes of arguments and environment data that can be passed in an exec function.
_SC_CHILD_MAX
Represents CHILD_MAX, as defined by the values returned by sysconf(), the maximum number of processes that a real user ID (UID) may have running simultaneously.
_SC_CLK_TCK
Represents the CLK_TCK macro defined in the time.h header file: the number of clock ticks in a second.
_SC_JOB_CONTROL
Represents the _POSIX_JOB_CONTROL macro that can be defined in the unistd.h header file. This indicates that certain job control operations are implemented by this version of the operating system. If _POSIX_JOB_CONTROL is defined, various functions (for example, setpgid()) have more functionality than when the macro is not defined.
_SC_NGROUPS_MAX
Represents NGROUPS_MAX, as defined by the values returned by sysconf(), the maximum number of supplementary group IDs (GIDs) that can be associated with a process.
_SC_OPEN_MAX
Represents OPEN_MAX, as defined by the values returned by sysconf(), the maximum number of files that a single process can have open at one time.
_SC_SAVED_IDS
Represents the _POSIX_SAVED_IDS macro, which may be defined in unistd.h header file, indicating that this POSIX implementation has a saved set UID and a saved set GID. This symbol affects the behavior of such functions as setuid() and setgid().
_SC_STREAM_MAX
Represents the _STREAM_MAX macro, which may be defined in the unistd.h header file, indicating the maximum number of streams that a process can have open at one time.
_SC_THREADS_MAX_NP
Represents the THREAD_MAX macro, as defined by the values returned by sysconf(), the maximum number of concurrent threads processed by pthread_create(), including running, queued, and exited undetached threads in the caller's process.
_SC_THREAD_TASKS_MAX_NP
Represents the THREAD_TASKS_MAX macro, as defined by the values returned by sysconf(), the maximum number of MVS™ tasks simultaneously in use for threads processed by pthread_create() in the caller's process.
_SC_TTY_GROUP
Retrieves the group number associated with the TTYGROUP() initialization parameter.
_SC_TZNAME_MAX
Represents the _TZNAME_MAX macro, which may be defined in the unistd.h header file, indicating the maximum length of the name of a time zone.
_SC_VERSION
Represents the _POSIX_VERSION macro, which will be defined in the unistd.h header file, indicating the version of the POSIX.1 standard that the system conforms to.
In addition to the symbols exposed by _POSIX_SOURCE, the following are visible when _XOPEN_SOURCE is defined:
_SC_XOPEN_CRYPT
Represents _XOPEN_CRYPT, the implementation supports the X/Open Encryption Option Group.
_SC_XOPEN_VERSION
Represents _XOPEN_VERSION, integer value indicating version of the X/Open Portability Guide to which the implementation conforms.
_SC_PASS_MAX
Represents PASS_MAX, as defined by the values returned by sysconf(), the maximum number of bytes allowed in a password, PassTicket, or password phrase.
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 function 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.
In addition to the symbols exposed by _XOPEN_SOURCE, the following are visible when _XOPEN_SOURCE_EXTENDED is defined to be 1:
_SC_PAGE_SIZE
Returns the current page size in bytes.
_SC_PAGESIZE
Returns the current page size in bytes.
In addition to the symbols exposed by _POSIX_SOURCE, the following are visible when _POSIX_C_SOURCE is defined to be 2:
_SC_2_C_BIND
Represents _POSIX2_C_BIND, the implementation supports the C-Language Binding option.
_SC_2_C_DEV
Represents _POSIX2_C_DEV, the implementation supports the C-Language Development Utilities option.
_SC_2_LOCALEDEF
Represents _POSIX2_LOCALEDEF, the implementation supports the creation of locales by the localedef utility.
_SC_2_UPE
Represents _POSIX2_UPE, the implementation supports the User Portability Utilities option. .
_SC_2_VERSION
Represents _POSIX2_VERSION, integer value indicating version of the Shell and Utilities to which the implementation conforms.
In addition to the symbols exposed by _POSIX_C_SOURCE defined to be 2, the following are visible when _POSIX_C_SOURCE is defined to be 200112L:
_SC_HOST_NAME_MAX
Represents HOST_NAME_MAX, Maximum length of a host name (not including the terminating null) as returned from the gethostname() function.
_SC_IPV6
Represents _POSIX_IPV6, the implementation supports the IPv6 option.
_SC_LOGIN_NAME_MAX
Represents LOGIN_NAME_MAX, Maximum length of a login name.
_SC_READER_WRITER_LOCKS
Represents _POSIX_READER_WRITER_LOCKS, the implementation supports the Read-Write Locks option. This is always set to a value greater than zero if the Threads option is supported.
_SC_REGEXP
Represents _POSIX_REGEXP, the implementation supports the Regular Expression Handling option.
_SC_SHELL
Represents _POSIX_SHELL, the implementation supports the POSIX shell.
_SC_SYMLOOP_MAX
Represents SYMLOOP_MAX, maximum number of symbolic links that can be reliably traversed in the resolution of a path name in the absence of a loop.
_SC_THREAD_ATTR_STACKSIZE
Represents _POSIX_THREAD_ATTR_STACKSIZE, the implementation supports the Thread Stack Size Attribute option.
_SC_THREAD_KEYS_MAX
Represents PTHREAD_KEYS_MAX, maximum number of data keys that can be created by a process.
_SC_THREAD_PROCESS_SHARED
Represents _POSIX_THREAD_PROCESS_SHARED, the implementation supports the Thread Process-Shared Synchronization option.
_SC_THREAD_SAFE_FUNCTIONS
Represents _POSIX_THREAD_SAFE_FUNCTIONS, the implementation supports the Thread-Safe Functions option.
_SC_THREAD_STACK_MIN
Represents PTHREAD_STACK_MIN, minimum size in bytes of thread stack storage.
_SC_THREAD_THREADS_MAX
Represents PTHREAD_THREADS_MAX, maximum number of threads that can be created per process.
_SC_THREADS
Represents _POSIX_THREADS, the implementation supports the Threads option.
_SC_TTY_NAME_MAX
Represents TTY_NAME_MAX, maximum length of terminal device name.
_SC_V6_ILP32_OFF32
Represents _POSIX_V6_ILP32_OFF32, the implementation provides a C-language compilation environment with 32-bit int, long, pointer, and off_t types.
_SC_V6_ILP32_OFFBIG
Represents _POSIX_V6_ILP32_OFFBIG, the implementation provides a C-language compilation environment with 32-bit int, long, and pointer types and an off_t type using at least 64 bits.
_SC_V6_LP64_OFF64
Represents _POSIX_V6_LP64_OFF64, the implementation provides a C-language compilation environment with 32-bit int and 64-bit long, pointer, and off_t types.
_SC_V6_LPBIG_OFFBIG
Represents _POSIX_V6_LPBIG_OFFBIG, the implementation provides a C-language compilation environment with an int type using at least 32 bits and long, pointer, and off_t types using at least 64 bits.
_SC_XOPEN_LEGACY
Represents _XOPEN_LEGACY, the implementation supports the Legacy Option Group.
The following symbols are available under _XOPEN_SOURCE 500:
_SC_GETPW_R_SIZE_MAX
Maximum size of getpwuid_r() and getpwnam_r() data buffers
_SC_GETGR_R_SIZE_MAX
Maximum size of getgrgid_r() and getgrnam_r() data buffers
If successful, sysconf() returns the value associated with the specified option.
If the variable corresponding to name exists but is not supported by the system, sysconf() returns -1 but does not change the value of errno. If sysconf() fails in some other way, it returns -1.
If unsuccessful, sysconf() sets errno to one of the following values:
EINVAL - The value specified for the name argument is incorrect.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* determine system configuration options by sysconf() function code example */
#define _POSIX_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
main() {
long result;
errno = 0;
puts("examining ARG_MAX limit");
if ((result = sysconf(_SC_ARG_MAX)) == -1)
if (errno == 0)
puts("ARG_MAX is not supported.");
else perror("sysconf() error");
else
printf("ARG_MAX is %ld\n", result);
}
In this c program, user is asked to entered the number of rows r and columns c. The value of r and c should be less than 10 in this program. The user is asked to enter elements of the...
This C Program to Calculates the value of nCr. The algorithm used in this program is nCr = n! /((n-r)!r!) and We need to Find all the Possible combination of the value n&r. A combination
First, create a file to sort, write unsorted data to disk and now, sort the file. Sorting disk file. A Quicksort for files. First read in record i and j and then write them back in opposite slots.
C language read elements in two matrices and find the difference of two matrices. Subtract two matrices in C. Elements of two matrices can only be subtracted if and only...
We have accept one string from the user and "character to be deleted" from the user. Pass these 'two parameters' to function which will "delete all occurrences" of the character from
C program code lexicographically compares two strings. Returns an integer based on the outcome. String1 is less than string2, string1 is equal to string2, string1 is greater than...