C Programming Code Examples
C > Small Programs Code Examples
Sort text data by soundex value
/* Sort text data by soundex value */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#define PACKAGE "sndsort"
#define VERSION "0.0.2"
#define MAXLINE 1024
struct lnode {
char *str;
int sndval;
struct lnode *next;
};
struct lnode *insert(char *data, int val, struct lnode *list);
char *soundex(char *str);
void free_list(struct lnode *list);
void print_list(struct lnode *list, int x);
void print_help(int exval);
int main(int argc, char *argv[]) {
FILE *fp = stdin; /* read input from... (default is stdin) */
struct lnode *list; /* linked list */
char line[MAXLINE]; /* buff for fgets() */
int sval = 0; /* return value from soundex() */
int len = 0; /* initial line length */
int opt = 0; /* holds getopt option nr ... */
int min_len = 2; /* ignore lines Shorter as length (default=2) */
int max_len = 20; /* ignore lines Longer as length (default=20) */
int out_sndx_flag = 0; /* output the `soundex value' for each string */
int strip_nl_flag = 0; /* strip trailing newlines from input */
while((opt = getopt(argc, argv, "hvxsn:N:f:")) != -1) {
switch(opt) {
case 'h':
print_help(0);
break;
case 'v':
exit(0);
break;
case 'x':
out_sndx_flag = 1;
break;
case 's':
strip_nl_flag = 1;
break;
case 'n':
min_len = atoi(optarg);
break;
case 'N':
max_len = atoi(optarg);
break;
case 'f':
if(freopen(optarg, "r", fp) == NULL) {
fprintf(stderr, "%s: Error - opening `%s'\n", PACKAGE, optarg);
return 1;
}
break;
case ':':
fprintf(stderr, "%s: Error - Option `%c' needs an argument\n\n", PACKAGE, optopt);
print_help(1);
case '?':
fprintf(stderr, "%s: Error - No such option: `%c'\n\n", PACKAGE, optopt);
print_help(1);
} /* switch */
} /* while */
list = NULL;
while((fgets(line, MAXLINE, stdin)) != NULL) {
len = strlen(line);
/* skip lines shorter as ``min_len'' in length */
if(len < min_len || len > max_len) continue;
/* strip trailing newlines */
if(strip_nl_flag == 1 && line[len - 1] == '\n')
line[len - 1] = '\0';
/* reverse line[] buffer */
sval = atoi(soundex(line));
/* insert line in the linked list */
list = insert(line, sval, list);
}
print_list(list, out_sndx_flag);
free_list(list);
fclose(fp);
return 0;
}
struct lnode *insert(char *data, int sval, struct lnode *list) {
struct lnode *p;
struct lnode *q;
/* create a new node */
p = (struct lnode *)malloc(sizeof(struct lnode));
/* save data into new node */
p->str = strdup(data);
p->sndval = sval;
/* first, we handle the case where `data' should be the first element */
if(list == NULL || list->sndval > sval) {
/* apperently this !IS! the first element */
/* now data should [be|becomes] the first element */
p->next = list;
return p;
} else {
/* search the linked list for the right location */
q = list;
while(q->next != NULL && q->next->sndval < sval) {
q = q->next;
}
p->next = q->next;
q->next = p;
return list;
}
}
void free_list(struct lnode *list) {
struct lnode *p;
while(list != NULL) {
p = list->next;
free(list->str);
free(list);
list = p;
}
}
void print_list(struct lnode *list, int x) {
struct lnode *p;
for(p = list; p != NULL; p = p->next)
if(x == 1)
printf("%8d %s\n", p->sndval, p->str);
else
printf("%s\n", p->str);
}
/* get soundex code for a string */
char *soundex(char *str) {
static char soundexbuf[81];
/*
// basicly ripped this piece of the code straight
// from the book... ehum.. sorry...
*/
char *table = "01230120022455012623010202";
char *sdx = soundexbuf, lastchr = ' ';
while(*str) {
if(isalpha(*str) && (*str != lastchr)) {
*sdx = *(table + toupper(*str) - 'A');
if((*sdx != '0') && (*sdx != lastchr))
lastchr = *sdx++;
}
str++;
}
*sdx = '\0';
return &soundexbuf[0];
}
void print_help(int exval) {
printf("%s,%s sort text data by soundex value\n", PACKAGE, VERSION);
printf("Usage: %s [-h] [-v] [-x] [-s] [-n INT] [-N INT] [-f FILE]\n\n", PACKAGE);
printf(" -h print this help and exit\n");
printf(" -v print version and exit\n\n");
printf(" -x output the `soundex value' with each string\n");
printf(" -s strip trailing newlines\n");
printf(" -n INT ignore lines Shorter as `INT' (default=2)\n");
printf(" -N INT ignore lines Longer as `INT' (default=20)\n");
printf(" -f FILE read input from `FILE' (default=stdin)\n\n");
exit(exval);
}
Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. The "malloc" or "memory allocation" method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn't Iniatialize memory at execution time so that it has initializes each block with the default garbage value initially.
The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.
Closes a file descriptor, fildes. This frees the file descriptor to be returned by future open() calls and other calls that create file descriptors. The fildes argument must represent a hierarchical file system (HFS) file. When the last open file descriptor for a file is closed, the file itself is closed. If the file's link count is 0 at that time, its space is freed and the file becomes inaccessible. When the last open file descriptor for a pipe or FIFO file is closed, any data remaining in the pipe or FIFO file is discarded. close() unlocks (removes) all outstanding record locks that a process has on the associated file. Behavior for sockets: close() call shuts down the socket associated with the socket descriptor socket, and frees resources allocated to the socket. If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed.
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).
The open() function shall establish the connection between a file and a file descriptor. It shall create an open file description that refers to a file and a file descriptor that refers to that open file description. The file descriptor is used by other I/O functions to refer to that file. The path argument points to a pathname naming the file. The open() function shall return a file descriptor for the named file that is the lowest file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor shall not share it with any other process in the system. The FD_CLOEXEC file descriptor flag associated with the new file descriptor shall be cleared.
The free() function in C library allows you to release or deallocate the memory blocks which are previously allocated by calloc(), malloc() or realloc() functions. It frees up the memory blocks and returns the memory to heap. It helps freeing the memory in your program which will be available for later use. In C, the memory for variables is automatically deallocated at compile time. For dynamic memory allocation in C, you have to deallocate the memory explicitly. If not done, you may encounter out of memory error.
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.
Convert string to integer. Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int. The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value.
The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control to pass to the conditional tests.
Write formatted data to stream. Writes the C string pointed by format to the stream. If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. After the format parameter, the function expects at least as many additional arguments as specified by format.
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).
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.
Convert lowercase letter to uppercase. Converts c to its uppercase equivalent if c is a lowercase letter and has an uppercase equivalent. If no such conversion is possible, the value returned is c unchanged. Notice that what is considered a letter may depend on the locale being used; In the default "C" locale, a lowercase letter is any of: a b c d e f g h i j k l m n o p q r s t u v w x y z, which translate respectively to: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z.
Duplicate a specific number of bytes from a string. The strdup() function shall return a pointer to a new string, which is a duplicate of the string pointed to by str. The returned pointer can be passed to free(). A null pointer is returned if the new string cannot be created. The function strdup() is used to duplicate a string. It returns a pointer to null-terminated byte string. strdup reserves storage space for a copy of string by calling malloc. The string argument to this function is expected to contain a null character (\0) marking the end of the string.
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.
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.
Check if character is alphabetic. Checks whether c is an alphabetic letter. Notice that what is considered a letter depends on the locale being used; In the default "C" locale, what constitutes a letter is only what returns true by either isupper or islower. Using other locales, an alphabetic character is a character for which isupper or islower would return true, or another character explicitly considered alphabetic by the locale (in this case, the character cannot be iscntrl, isdigit, ispunct or isspace).
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,
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.
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.
Get string from stream. Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str. A terminating null character is automatically appended after the characters copied to str. Notice that fgets is quite different from gets: not only fgets accepts a stream argument, but also allows to specify the maximum size of str and includes in the string any ending newline character.
In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.
Close file. Closes the file associated with the stream and disassociates it. All internal buffers associated with the stream are disassociated from it and flushed: the content of any unwritten output buffer is written and the content of any unread input buffer is discarded. Even if the call fails, the stream passed as parameter will no longer be associated with the file nor its buffers.
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.
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.
The getopt() function is a builtin function in C and is used to parse command line arguments. The getopt() function is a command-line parser that shall follow Utility Syntax Guidelines 3, 4, 5, 6, 7, 9, and 10 in the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines. The parameters argc and argv are the argument count and argument array as passed to main() (see exec() ). The argument optstring is a string of recognized option characters; if a character is followed by a colon, the option takes an argument. All option characters allowed by Utility Syntax Guideline 3 are allowed in optstring. The implementation may accept other characters as an extension.
#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:
Reopen stream with different file or mode. Reuses stream to either open the file specified by filename or to change its access mode. If a new filename is specified, the function first attempts to close any file already associated with stream (third parameter) and disassociates it. Then, independently of whether that stream was successfuly closed or not, freopen opens the file specified by filename and associates it with the stream just as fopen would do using the specified mode. If filename is a null pointer, the function attempts to change the mode of the stream. Although a particular library implementation is allowed to restrict the changes permitted, and under which circumstances. The error indicator and eof indicator are automatically cleared (as if clearerr was called).
C Program increments every element of the array by one & print array. We need to add 1 to all the elemnts of the given array. After adding 1 to all the elements of an array print
C program to read elements in an array and find its reverse. C Program to print reverse of an array. There are various ways to reverse an array. The basic three algorithms to reverse a
C program to find factorial of a number using recursion. The factorial of a 'positive number' n is given by: factorial of n (n!) = 1*2*3*4....n The factorial of a 'negative number' does not
Give a meaningful name to the function, say sumOfNaturalNumbers(). The function must accept two inputs i.e. the lower & upper limit to find sum. Pass two integer parameters to
In C, we are setting up the pointer to the base address of array and then we're incrementing pointer and using * operator to get & sum-up the values of all the array elements. Enter the
Input upper limit to find sum of even number. Store it in a variable say N. Initialize another variable to store sum with 0 say sum = 0. To find sum of even numbers we need to iterate
The above logic is simple & easy to code. But it's lengthy and not optimal to implement. In the above solution we are performing same task for multiple conditions i.e. print 31 days