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 > C on Unix Code Examples

String manipulation using message Queue

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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
/* String manipulation using message Queue */ Queue.h ------- #include<stdio.h> #include<errno.h> #include<sys/ipc.h> #include<sys/msg.h> struct queue { long type; char msg[50]; }; Queue.c ------- #include "queue.h" int main() { struct queue q; int mid; if((mid=msgget(ftok("string",0x99),0644|IPC_CREAT))<0) { if(mid!=-1) { printf("Message Queue Error "); exit(1); } else { printf("Message Already Exist "); exit(1); } } printf(" Enter the Message Type:"); scanf("%d",&q.type); while(q.type>0) { printf(" Enter the Message:"); getchar(); gets(q.msg); if(msgsnd(mid,&q,sizeof(q),IPC_NOWAIT)<0) { printf("Message send Error "); exit(1); } printf(" Enter the Message Type:"); scanf("%d",&q.type); } return 0; } Word.c ------ #include "queue.h" #include<string.h> void word(char* str) { int i,n,w=1; n=strlen(str); for(i=0;i<n;i++) if(str[i]==' ' && str[i-1]!=' ') w++; printf("Number of Words in "%s" :%d ",str,w); } int main() { struct queue q; int mid; long type; if((mid=msgget(ftok("string",0x99),0644 ))<0) { printf("Message Queue Error "); exit(1); } printf(" Enter the Message Type to Reterive:"); scanf("%d",&type); while(msgrcv(mid,&q,sizeof(q),type,IPC_NOWAIT) && errno!=ENOMSG) { word(q.msg); } msgctl(mid,IPC_RMID,NULL); } Reverse.c --------- #include "queue.h" #include<string.h> void rev(char* str) { char s[30]; int i,j,n; n=strlen(str); printf("Reverse for "%s" :",str); for(i=n;i>=0;i--) putchar(str[i]); printf(" "); } int main() { struct queue q; int mid; long type; if((mid=msgget(ftok("string",0x99),0644 ))<0) { printf("Message Queue Error "); exit(1); } printf(" Enter the Message Type to Reterive:"); scanf("%d",&type); while(msgrcv(mid,&q,sizeof(q),type,IPC_NOWAIT) && errno!=ENOMSG) { rev(q.msg); } }
msgctl() Function in C
The msgctl() function operates on XSI message queues (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.224, Message Queue). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime. The msgctl() function shall provide message control operations as specified by cmd.
Syntax for msgctl() Function in C
#include <sys/msg.h> int msgctl(int msqid, int cmd, struct msqid_ds *buf);
The following values for cmd, and the message control operations they specify, are: IPC_STAT: Place the current value of each member of the msqid_ds data structure associated with msqid into the structure pointed to by buf. The contents of this structure are defined in <sys/msg.h>. IPC_SET: Set the value of the following members of the msqid_ds data structure associated with msqid to the corresponding value found in the structure pointed to by buf: msg_perm.uid msg_perm.gid msg_perm.mode msg_qbytes IPC_SET can only be executed by a process with appropriate privileges or that has an effective user ID equal to the value of msg_perm.cuid or msg_perm.uid in the msqid_ds data structure associated with msqid. Only a process with appropriate privileges can raise the value of msg_qbytes. IPC_RMID: Remove the message queue identifier specified by msqid from the system and destroy the message queue and msqid_ds data structure associated with it. IPC_RMD can only be executed by a process with appropriate privileges or one that has an effective user ID equal to the value of msg_perm.cuid or msg_perm.uid in the msqid_ds data structure associated with msqid. Upon successful completion, msgctl() shall return 0; otherwise, it shall return -1 and set errno to indicate the error. The msgctl() function shall fail if:
EACCES
The argument cmd is IPC_STAT and the calling process does not have read permission; see XSI Interprocess Communication.
EINVAL
The value of msqid is not a valid message queue identifier; or the value of cmd is not a valid command.
EPERM
The argument cmd is IPC_RMID or IPC_SET and the effective user ID of the calling process is not equal to that of a process with appropriate privileges and it is not equal to the value of msg_perm.cuid or msg_perm.uid in the data structure associated with msqid.
EPERM
The argument cmd is IPC_SET, an attempt is being made to increase to the value of msg_qbytes, and the effective user ID of the calling process does not have appropriate privileges. The POSIX Realtime Extension defines alternative interfaces for interprocess communication (IPC). Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.
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
/* It performs various operations on a queue. Generally it is use to destroy message queue */ // C Program for Message Queue (Reader Process) #include <stdio.h> #include <sys/ipc.h> #include <sys/msg.h> // structure for message queue struct mesg_buffer { long mesg_type; char mesg_text[100]; } message; int main() { key_t key; int msgid; // ftok to generate unique key key = ftok("progfile", 65); // msgget creates a message queue // and returns identifier msgid = msgget(key, 0666 | IPC_CREAT); // msgrcv to receive message msgrcv(msgid, &message, sizeof(message), 1, 0); // display the message printf("Data Received is : %s \n", message.mesg_text); // to destroy the message queue msgctl(msgid, IPC_RMID, NULL); return 0; }
ftok() Function in C
The ftok() function returns a key based on path and id that is usable in subsequent calls to msgget(), semget(), and shmget(). The path argument must be the path name of an existing file that the process is able to stat(). The ftok() function returns the same key value for all paths that name the same file, when called with the same id value. If a different id value is given, or a different file is given, a different key is returned. Only the low-order 8-bits of id are significant, and must be nonzero.
Syntax for ftok() Function in C
#include <sys/ipc.h> key_t ftok(const char *path, int id);
path
Points to a path upon which part of the key is formed.
id
Is the character upon which part of the key is formed. The ftok() function does not guarantee unique key generation. The key is created by combining the given id byte, the lower 16 bits of the inode number, and the lower 8 bits of the device number into a 32-bit result. The occurrence of key duplication is very rare. If successful, ftok() returns a key. If unsuccessful, ftok() returns -1 and sets errno to one of the following values:
EACCES
Search permission is denied for a component of the path prefix.
EINVAL
The low-order 8-bits of id are zero.
ELOOP
Too many symbolic links were encountered in resolving path.
ENAMETOOLONG
One of the following error conditions exists: • The length of the path argument exceeds PATH_MAX or a path name component is longer than NAME_MAX. • The path name resolution of a symbolic link produced an intermediate result whose length exceeds PATH_MAX.
ENOENT
A component of path does not name an existing file or path is an empty string.
ENOTDIR
A component of the path prefix is not a directory.
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
/* generate an interprocess communication (IPC) key by ftok() function code example */ int main() { int qid; key_t key; int len,i; struct message msg; /*Generate standard keys based on different paths and key representations */ if ((key = ftok("/", 'a')) == -1) { perror("ftok"); exit(1); } /*Create message queue key */ if ((qid = msgget(key,IPC_CREAT|0666)) == -1) { perror("msgget"); exit(1); } printf("Opened queue %d\n",qid); puts("Please enter the message to queue:"); for (i=0;i<3;i++) { if ((fgets((&msg)->msg_text, BUFSZ, stdin)) == NULL) { puts("no message"); exit(1); } msg.msg_type = getpid()+i; len = strlen(msg.msg_text); /*add message to message queue */ if ((msgsnd(qid, &msg, len, 0)) < 0) { perror("message posted"); exit(1); } } /*read message queue */ for (i=0;i<3;i++) { if (msgrcv(qid, &msg, BUFSZ, getpid()+2-i, 0) < 0) { perror("msgrcv"); exit(1); } printf("message is:%s\n",(&msg)->msg_text); } /* Remove the message queue from the system kernel */ if ((msgctl(qid, IPC_RMID, NULL)) < 0) { perror("msgctl"); exit(1); } exit(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; }
msgget() Function in C
The msgget() function operates on XSI message queues (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.224, Message Queue). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime. The msgget() function shall return the message queue identifier associated with the argument key.
Syntax for msgget() Function in C
#include <sys/msg.h> int msgget(key_t key, int msgflg);
A message queue identifier, associated message queue, and data structure (see <sys/msg.h>), shall be created for the argument key if one of the following is true: • The argument key is equal to IPC_PRIVATE. • The argument key does not already have a message queue identifier associated with it, and (msgflg & IPC_CREAT) is non-zero. Upon creation, the data structure associated with the new message queue identifier shall be initialized as follows: • msg_perm.cuid, msg_perm.uid, msg_perm.cgid, and msg_perm.gid shall be set equal to the effective user ID and effective group ID, respectively, of the calling process. • The low-order 9 bits of msg_perm.mode shall be set equal to the low-order 9 bits of msgflg. • msg_qnum, msg_lspid, msg_lrpid, msg_stime, and msg_rtime shall be set equal to 0. • msg_ctime shall be set equal to the current time. • msg_qbytes shall be set equal to the system limit. Upon successful completion, msgget() shall return a non-negative integer, namely a message queue identifier. Otherwise, it shall return -1 and set errno to indicate the error. The msgget() function shall fail if:
EACCES
A message queue identifier exists for the argument key, but operation permission as specified by the low-order 9 bits of msgflg would not be granted; see XSI Interprocess Communication.
EEXIST
A message queue identifier exists for the argument key but ((msgflg & IPC_CREAT) && (msgflg & IPC_EXCL)) is non-zero.
ENOENT
A message queue identifier does not exist for the argument key and (msgflg & IPC_CREAT) is 0.
ENOSPC
A message queue identifier is to be created but the system-imposed limit on the maximum number of allowed message queue identifiers system-wide would be exceeded.
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
/* return the message queue identifier associated with the argument key by msgget() function code example */ /* either returns the message queue identifier for a newly created message queue or returns the identifiers for a queue which exists with the same key value */ // C Program for Message Queue (Writer Process) #include <stdio.h> #include <sys/ipc.h> #include <sys/msg.h> #define MAX 10 // structure for message queue struct mesg_buffer { long mesg_type; char mesg_text[100]; } message; int main() { key_t key; int msgid; // ftok to generate unique key key = ftok("progfile", 65); // msgget creates a message queue // and returns identifier msgid = msgget(key, 0666 | IPC_CREAT); message.mesg_type = 1; printf("Write Data : "); fgets(message.mesg_text,MAX,stdin); // msgsnd to send message msgsnd(msgid, &message, sizeof(message), 0); // display the message printf("Data send is : %s \n", message.mesg_text); 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; }
getchar() Function in C
Get character from stdin. Returns the next character from the standard input (stdin). It is equivalent to calling getc with stdin as argument. A getchar() function is a non-standard function whose meaning is already defined in the stdin.h header file to accept a single input from the user. In other words, it is the C library function that gets a single character (unsigned char) from the stdin. However, the getchar() function is similar to the getc() function, but there is a small difference between the getchar() and getc() function of the C programming language. A getchar() reads a single character from standard input, while a getc() reads a single character from any input stream.
Syntax for getchar() Function in C
#include <stdio.h> int getchar ( void );
On success, the character read is returned (promoted to an int value). The return type is int to accommodate for the special value EOF, which indicates failure: If the standard input was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stdin. If some other reading error happens, the function also returns EOF, but sets its error indicator (ferror) instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* gets a single character (unsigned char) from the stdin by getchar() function example */ #include <stdio.h> #include <ctype.h> int main() { int ch, i = 0; char str[150]; printf (" Enter the characters from the keyboard (Press Enter button to stop).\n"); // use do while loop to define the condition do { ch = getchar(); // takes character, number, etc from the user str[i] = ch; // store the ch into str[i] i++; // increment loop by 1 } while (ch != '\n'); // ch is not equal to '\n' printf("Entered characters are %s ", str); return 0; }
scanf() Function in C
Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string. In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.
Syntax for scanf() Function in C
#include <stdio.h> int scanf ( const char * format, ... );
format
C string that contains a sequence of characters that control how characters extracted from the stream are treated: • Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none). • Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread. • Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments. A format specifier for scanf follows this prototype: %[*][width][length]specifier
specifier
Where the specifier character at the end is the most significant component, since it defines which characters are extracted, their interpretation and the type of its corresponding argument:
i – integer
Any number of digits, optionally preceded by a sign (+ or -). Decimal digits assumed by default (0-9), but a 0 prefix introduces octal digits (0-7), and 0x hexadecimal digits (0-f). Signed argument.
d or u – decimal integer
Any number of decimal digits (0-9), optionally preceded by a sign (+ or -). d is for a signed argument, and u for an unsigned.
o – octal integer
Any number of octal digits (0-7), optionally preceded by a sign (+ or -). Unsigned argument.
x – hexadecimal integer
Any number of hexadecimal digits (0-9, a-f, A-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -). Unsigned argument.
f, e, g – floating point number
A series of decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer (or some of the other sequences supported by strtod). Implementations complying with C99 also support hexadecimal floating-point format when preceded by 0x or 0X.
c – character
The next character. If a width other than 1 is specified, the function reads exactly width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.
s – string of characters
Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
p – pointer address
A sequence of characters representing a pointer. The particular format used depends on the system and library implementation, but it is the same as the one used to format %p in fprintf.
[characters] – scanset
Any number of the characters specified between the brackets. A dash (-) that is not the first character may produce non-portable behavior in some library implementations.
[^characters] – negated scanset
Any number of characters none of them specified as characters between the brackets.
n – count
No input is consumed. The number of characters read so far from stdin is stored in the pointed location.
%
A % followed by another % matches a single %. Except for n, at least one character shall be consumed by any specifier. Otherwise the match fails, and the scan ends there.
sub-specifier
The format specifier can also contain sub-specifiers: asterisk (*), width and length (in that order), which are optional and follow these specifications:
*
An optional starting asterisk indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an argument).
width
Specifies the maximum number of characters to be read in the current reading operation (optional).
length
One of hh, h, l, ll, j, z, t, L (optional). This alters the expected type of the storage pointed by the corresponding argument (see below).
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a pointer to allocated storage where the interpretation of the extracted characters is stored with the appropriate type. There should be at least as many of these arguments as the number of values stored by the format specifiers. Additional arguments are ignored by the function. These arguments are expected to be pointers: to store the result of a scanf operation on a regular variable, its name should be preceded by the reference operator (&) (see example). On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file. If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned. If an encoding error happens interpreting wide characters, the function sets errno to EILSEQ.
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
/* read formatted data from stdin by scanf() function example */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, const char * argv[]) { /* Define temporary variables */ char name[10]; int age; int result; /* Ask the user to enter their first name and age */ printf("Please enter your first name and your age.\n"); /* Read a name and age from the user */ result = scanf("%s %d",name, &age); /* We were not able to parse the two required values */ if (result < 2) { /* Display an error and exit */ printf("Either name or age was not entered\n\n"); exit(0); } /* Display the values the user entered */ printf("Name: %s\n", name); printf("Age: %d\n", age); return 0; }
msgsnd() Function in C
The msgsnd() function operates on XSI message queues (see the Base Definitions volume of IEEE Std 1003.1-2001, Section 3.224, Message Queue). It is unspecified whether this function interoperates with the realtime interprocess communication facilities defined in Realtime. The msgsnd() function shall send a message to the queue associated with the message queue identifier specified by msqid.
Syntax for msgsnd() Function in C
#include <sys/msg.h> int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
The application shall ensure that the argument msgp points to a user-defined buffer that contains first a field of type long specifying the type of the message, and then a data portion that holds the data bytes of the message. The structure below is an example of what this user-defined buffer might look like:
struct mymsg { long mtype; /* Message type. */ char mtext[1]; /* Message text. */ }
The structure member mtype is a non-zero positive type long that can be used by the receiving process for message selection. The structure member mtext is any text of length msgsz bytes. The argument msgsz can range from 0 to a system-imposed maximum. The argument msgflg specifies the action to be taken if one or more of the following is true: • The number of bytes already on the queue is equal to msg_qbytes; see <sys/msg.h>. • The total number of messages on all queues system-wide is equal to the system-imposed limit. These actions are as follows: • If (msgflg & IPC_NOWAIT) is non-zero, the message shall not be sent and the calling thread shall return immediately. • If (msgflg & IPC_NOWAIT) is 0, the calling thread shall suspend execution until one of the following occurs: – The condition responsible for the suspension no longer exists, in which case the message is sent. – The message queue identifier msqid is removed from the system; when this occurs, errno shall be set equal to [EIDRM] and -1 shall be returned. – The calling thread receives a signal that is to be caught; in this case the message is not sent and the calling thread resumes execution in the manner prescribed in sigaction(). Upon successful completion, the following actions are taken with respect to the data structure associated with msqid; see <sys/msg.h>: • msg_qnum shall be incremented by 1. • msg_lspid shall be set equal to the process ID of the calling process. • msg_stime shall be set equal to the current time. Upon successful completion, msgsnd() shall return 0; otherwise, no message shall be sent, msgsnd() shall return -1, and errno shall be set to indicate the error. The msgsnd() function shall fail if:
EACCES
Operation permission is denied to the calling process; see XSI Interprocess Communication.
EAGAIN
The message cannot be sent for one of the reasons cited above and (msgflg & IPC_NOWAIT) is non-zero.
EIDRM
The message queue identifier msqid is removed from the system.
EINTR
The msgsnd() function was interrupted by a signal.
EINVAL
The value of msqid is not a valid message queue identifier, or the value of mtype is less than 1; or the value of msgsz is less than 0 or greater than the system-imposed limit. The POSIX Realtime Extension defines alternative interfaces for interprocess communication (IPC). Application developers who need to use IPC should design their applications so that modules using the IPC routines described in XSI Interprocess Communication can be easily modified to use the alternative interfaces.
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
/* data is placed on to a message queue by calling msgsnd() */ // C Program for Message Queue (Writer Process) #include <stdio.h> #include <sys/ipc.h> #include <sys/msg.h> #define MAX 10 // structure for message queue struct mesg_buffer { long mesg_type; char mesg_text[100]; } message; int main() { key_t key; int msgid; // ftok to generate unique key key = ftok("progfile", 65); // msgget creates a message queue // and returns identifier msgid = msgget(key, 0666 | IPC_CREAT); message.mesg_type = 1; printf("Write Data : "); fgets(message.mesg_text,MAX,stdin); // msgsnd to send message msgsnd(msgid, &message, sizeof(message), 0); // display the message printf("Data send is : %s \n", message.mesg_text); return 0; }
Logical Operators in C
An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. These operators are used to perform logical operations and used with conditional statements like C if-else statements.
&&
Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
||
Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.
!
Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false.
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
/* logical operators in C language */ #include <stdio.h> main() { int a = 4; int b = 23; int c ; if ( a && b ) { printf("Line 1 - Condition is true\n" ); } if ( a || b ) { printf("Line 2 - Condition is true\n" ); } /* lets change the value of a and b */ a = 2; b = 8; if ( a && b ) { printf("Line 3 - Condition is true\n" ); } else { printf("Line 3 - Condition is not true\n" ); } if ( !(a && b) ) { printf("Line 4 - Condition is true\n" ); } }
strlen() Function in C
Get string length. Returns the length of the C string str. The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
Syntax for strlen() Function in C
#include <string.h> size_t strlen ( const char * str );
str
C string Function returns the length of string. This should not be confused with the size of the array that holds the string. strlen() function is defined in string.h header file. It doesn't count null character '\0'.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/* get the length of the C string str by strlen() function example */ /* Program to find the total length of a String using strlen() */ #include<stdio.h> #include<string.h> int main() { char str1[10]= "01234567"; /* First string */ printf("First String is %s",str1); printf("\n"); int length = strlen(str1); printf("Length of first String is %d", length); printf("\n"); char str2[20]= "String Chapter"; /* Second string */ printf("Second String is %s",str2); printf("\n"); length = strlen(str2); printf("Length of second String is %d", length); return 0; }
msgrcv() Function in C
The msgrcv() function reads a message from the queue associated with the message queue identifier specified by msqid and places it in the user-defined buffer pointed to by msgp. The argument msgp points to a user-defined buffer that must contain first a field of type long int that will specify the type of the message, and then a data portion that will hold the data bytes of the message. The structure below is an example of what this user-defined buffer might look like:
struct mymsg { long int mtype; /* message type */ char mtext[1]; /* message text */ }
The structure member mtype is the received message's type as specified by the sending process. The structure member mtext is the text of the message. The argument msgsz specifies the size in bytes of mtext. The received message is truncated to msgsz bytes if it is larger than msgsz and (msgflg & MSG_NOERROR) is non-zero. The truncated part of the message is lost and no indication of the truncation is given to the calling process. If the value of msgsz is greater than {SSIZE_MAX}, the result is implementation-dependent.
Syntax for msgrcv() Function in C
#include <sys/msg.h> ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long int msgtyp, int msgflg);
The argument msgtyp specifies the type of message requested as follows: • If msgtyp is 0, the first message on the queue is received. • If msgtyp is greater than 0, the first message of type msgtyp is received. • If msgtyp is less than 0, the first message of the lowest type that is less than or equal to the absolute value of msgtyp is received. The argument msgflg specifies the action to be taken if a message of the desired type is not on the queue. These are as follows: • If (msgflg & IPC_NOWAIT) is non-zero, the calling thread will return immediately with a return value of -1 and errno set to [ENOMSG]. • If (msgflg & IPC_NOWAIT) is 0, the calling thread will suspend execution until one of the following occurs: – A message of the desired type is placed on the queue. – The message queue identifier msqid is removed from the system; when this occurs, errno is set equal to [EIDRM] and -1 is returned. – The calling thread receives a signal that is to be caught; in this case a message is not received and the calling thread resumes execution in the manner prescribed in sigaction(). Upon successful completion, the following actions are taken with respect to the data structure associated with msqid: • msg_qnum is decremented by 1. • msg_lrpid is set equal to the process ID of the calling process. • msg_rtime is set equal to the current time. Upon successful completion, msgrcv() returns a value equal to the number of bytes actually placed into the buffer mtext. Otherwise, no message will be received, msgrcv() will return (ssize_t)-1 and errno will be set to indicate the error. The msgrcv() function will fail if:
E2BIG
The value of mtext is greater than msgsz and (msgflg & MSG_NOERROR) is 0.
EACCES
Operation permission is denied to the calling process. See IPC.
EIDRM
The message queue identifier msqid is removed from the system.
EINTR
The msgrcv() function was interrupted by a signal.
EINVAL
msqid is not a valid message queue identifier.
ENOMSG
The queue does not contain a message of the desired type and (msgflg & IPC_NOWAIT) is non-zero. The POSIX Realtime Extension defines alternative interfaces for interprocess communication. Application developers who need to use IPC should design their applications so that modules using the IPC routines described in IPC can be easily modified to use the alternative interfaces.
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
/* reading a message from a specified message queue whose identifier is supplied by msgrcv() function code example */ /* messages are retrieved from a queue. */ // C Program for Message Queue (Reader Process) #include <stdio.h> #include <sys/ipc.h> #include <sys/msg.h> // structure for message queue struct mesg_buffer { long mesg_type; char mesg_text[100]; } message; int main() { key_t key; int msgid; // ftok to generate unique key key = ftok("progfile", 65); // msgget creates a message queue // and returns identifier msgid = msgget(key, 0666 | IPC_CREAT); // msgrcv to receive message msgrcv(msgid, &message, sizeof(message), 1, 0); // display the message printf("Data Received is : %s \n", message.mesg_text); // to destroy the message queue msgctl(msgid, IPC_RMID, NULL); return 0; }
exit() Function in C
The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program. The exit() function is the standard library function of the C, which is defined in the stdlib.h header file. So, we can say it is the function that forcefully terminates the current program and transfers the control to the operating system to exit the program. The exit(0) function determines the program terminates without any error message, and then the exit(1) function determines the program forcefully terminates the execution process.
Syntax for exit() Function in C
#include <stdlib.h> void exit(int status)
status
Status code. If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure. The exit function does not return anything. • We must include the stdlib.h header file while using the exit () function. • It is used to terminate the normal execution of the program while encountered the exit () function. • The exit () function calls the registered atexit() function in the reverse order of their registration. • We can use the exit() function to flush or clean all open stream data like read or write with unwritten buffered data. • It closed all opened files linked with a parent or another function or file and can remove all files created by the tmpfile function. • The program's behaviour is undefined if the user calls the exit function more than one time or calls the exit and quick_exit function. • The exit function is categorized into two parts: exit(0) and exit(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 25 26
/* call all functions registered with atexit and terminates the program by exit() function example */ #include <stdio.h> #include <stdlib.h> int main () { // declaration of the variables int i, num; printf ( " Enter the last number: "); scanf ( " %d", &num); for ( i = 1; i<num; i++) { // use if statement to check the condition if ( i == 6 ) /* use exit () statement with passing 0 argument to show termination of the program without any error message. */ exit(0); else printf (" \n Number is %d", i); } return 0; }
If Else If Ladder in C/C++
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax of if...else Ladder in C
if (Condition1) { Statement1; } else if(Condition2) { Statement2; } . . . else if(ConditionN) { StatementN; } else { Default_Statement; }
In the above syntax of if-else-if, if the Condition1 is TRUE then the Statement1 will be executed and control goes to next statement in the program following if-else-if ladder. If Condition1 is FALSE then Condition2 will be checked, if Condition2 is TRUE then Statement2 will be executed and control goes to next statement in the program following if-else-if ladder. Similarly, if Condition2 is FALSE then next condition will be checked and the process continues. If all the conditions in the if-else-if ladder are evaluated to FALSE, then Default_Statement will be executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* write a C program which demonstrate use of if-else-if ladder statement */ #include<stdio.h> #include<conio.h> void main() { int a; printf("Enter a Number: "); scanf("%d",&a); if(a > 0) { printf("Given Number is Positive"); } else if(a == 0) { printf("Given Number is Zero"); } else if(a < 0) { printf("Given Number is Negative"); } getch(); }
For Loop Statement in C
The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.
Syntax of For Loop Statement in C
for (initialization; condition test; increment or decrement) { //Statements to be executed repeatedly }
Step 1
First initialization happens and the counter variable gets initialized.
Step 2
In the second step the condition is checked, where the counter variable is tested for the given condition, if the condition returns true then the C statements inside the body of for loop gets executed, if the condition returns false then the for loop gets terminated and the control comes out of the loop.
Step 3
After successful execution of statements inside the body of loop, the counter variable is incremented or decremented, depending on the operation (++ or --).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* for loop statement in C language */ // Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include <stdio.h> int main() { int num, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); // for loop terminates when num is less than count for(count = 1; count <= num; ++count) { sum += count; } printf("Sum = %d", sum); 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(); }
putchar() Function in C
Write character to stdout. Writes a character to the standard output (stdout). It is equivalent to calling putc with stdout as second argument. putchar() function is a file handling function in C programming language which is used to write a character on standard output/screen. The putchar() function is used for printing character to a screen at current cursor location. It is unformatted character output functions. It is defined in header file stdio.h.
Syntax for putchar() Function in C
#include <stdio.h> int putchar ( int character );
character
The int promotion of the character to be written. The value is internally converted to an unsigned char when written. The character which is read is an unsigned char which is converted to an integer value. In the case of file handling, it returns EOF when end-of-file is encountered. If there is an error then it also returns EOF. On success, the character written is returned. If a writing error occurs, EOF is returned and the error indicator (ferror) is set.
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
/* write a character to the standard output (stdout) by putchar() function example */ #include <stdio.h> #include <stdlib.h> int main() { //Initialize the character array char str[100]; int i = 0, j = 0; printf("Enter the string into the file\n"); //takes all the characters until enter is pressed while ((str[i] = getchar()) != '\n') { //increment the index of the character array i++; } //after taking all the character add //null pointer at the end of the string str[i] = '\0'; printf("\nThe file content is - "); //loop is break when null pointer is encountered while (str[j] != '\0') { //print the characters putchar(str[j]); j++; } return 0; }
While Loop Statement in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.
Syntax of While Loop Statement in C
while (testExpression) { // the body of the loop }
• The while loop evaluates the testExpression inside the parentheses (). • If testExpression is true, statements inside the body of while loop are executed. Then, testExpression is evaluated again. • The process goes on until testExpression is evaluated to false. • If testExpression is false, the loop terminates (ends).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* while loop statement in C language */ #include<stdio.h> int main() { int n, num, sum = 0, remainder; printf("Enter a number: "); scanf("%d", &n); num = n; // keep looping while n > 0 while( n > 0 ) { remainder = n % 10; // get the last digit of n sum += remainder; // add the remainder to the sum n /= 10; // remove the last digit from n } printf("Sum of digits of %d is %d", num, sum); // signal to operating system everything works fine return 0; }
#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; }
sizeof() Operator in C
The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.
Syntax for sizeof() Operator in C
#include <stdio.h> sizeof (data type)
data type
Where data type is the desired data type including classes, structures, unions and any other user defined data type. Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() 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
/* return the size of a variable by sizeof() operator example */ int main( int argc, char* argv[] ) { printf("sizeof(char) = %d\n", sizeof(char) ); printf("sizeof(short) = %d\n", sizeof(short) ); printf("sizeof(int) = %d\n", sizeof(int) ); printf("sizeof(long) = %d\n", sizeof(long) ); printf("sizeof(long long) = %d\n", sizeof(long long) ); printf("\n"); printf("sizeof(unsigned char) = %d\n", sizeof(unsigned char) ); printf("sizeof(unsigned short) = %d\n", sizeof(unsigned short) ); printf("sizeof(unsigned int) = %d\n", sizeof(unsigned int) ); printf("sizeof(unsigned long) = %d\n", sizeof(unsigned long) ); printf("\n"); printf("sizeof(float) = %d\n", sizeof(float) ); printf("sizeof(double) = %d\n", sizeof(double) ); printf("sizeof(long double) = %d\n", sizeof(long double) ); printf("\n"); int x; printf("sizeof(x) = %d\n", sizeof(x) ); }


C program to input any decimal number from user and convert it to binary number system using bitwise operator. How to convert from decimal number system to binary number...
Create a structure. The name of the structure is StudentData. The Student is the variable of structure StudentData. Assigning the values of each struct member here. Displaying the...
C Program accepts the sorted array and does search using "Binary Search". Binary search is algorithm for locating the position of an item in a 'Sorted Array'. A search of sorted data, in
Enter the Name of the Custumer. Enter the Acc.no of the Custumer. Enter the Balance of the Custumer. Enter the name of Customer whose rec. is to be modified. Enter the new
Program accepts a string and checks whether a given string is 'Palindrome'. Take a string as input & store it in the array string[]. Store the same string into the another array 'reverse_s'
C Programming code implements two Stacks using a Single Array & Check for Overflow & Underflow. A Stack is a linear data structure in which a data item is inserted and deleted...
Input few numbers & perform 'Merge Sort' on them using recursion. C program to performs merge sort. Merge sort is a sorting algorithm with complexity of O(nlogn) and It is used for