C Programming Code Examples
C > Small Programs Code Examples
Sort text data by rhyming order
/* Sort text data by rhyming order */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#define PACKAGE "rhymsort"
#define VERSION "0.0.2"
#define MAXLINE 1024
struct lnode {
char *str;
struct lnode *next;
};
struct lnode *insert(char *data, struct lnode *list);
void free_list(struct lnode *list);
void print_list(struct lnode *list, int r);
void rev(char *str);
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 len = 0; /* initial line length */
int opt = 0; /* holds getopt option nr ... */
int min_len = 2; /* minimumn accepted length of incomming lines */
int out_rev_flag = 0; /* output the `raw' reversed lines */
int strip_nl_flag = 0; /* strip trailing newlines from input */
while((opt = getopt(argc, argv, "hvrsn:f:")) != -1) {
switch(opt) {
case 'h':
print_help(0);
break;
case 'v':
exit(0);
break;
case 'r':
out_rev_flag = 1;
break;
case 's':
strip_nl_flag = 1;
break;
case 'n':
min_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) continue;
/* strip trailing newlines */
if(strip_nl_flag == 1 && line[len - 1] == '\n')
line[len - 1] = '\0';
/* reverse line[] buffer */
rev(line);
/* insert line in the linked list */
list = insert(line, list);
}
print_list(list, out_rev_flag);
free_list(list);
fclose(fp);
return 0;
}
struct lnode *insert(char *data, 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);
/* first, we handle the case where `data' should be the first element */
if(list == NULL || strcmp(list->str, data) > 0) {
/* 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 && strcmp(q->next->str, data) < 0) {
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);
list = p;
}
}
void print_list(struct lnode *list, int r) {
struct lnode *p;
for(p = list; p != NULL; p = p->next)
if(r == 0)
rev(p->str), printf("%s\n", p->str);
else
printf("%s\n", p->str);
}
/* reverse string ... */
void rev(char *str) {
char temp = 0;
char *end = NULL;
/* point to last non-NULL character in str */
end = str + strlen(str) - 1;
while(str < end)
temp = *str, *str++ = *end, *end-- = temp;
}
void print_help(int exval) {
printf("%s,%s sort text data by rhyming order\n", PACKAGE, VERSION);
printf("Usage: %s [-h] [-v] [-r] [-s] [-n INT] [-f FILE]\n\n", PACKAGE);
printf(" -h print this help and exit\n");
printf(" -v print version and exit\n\n");
printf(" -r output the `raw' reversed lines\n");
printf(" -s strip trailing newlines\n");
printf(" -n INT ignore lines shorter as `INT' (default=2)\n");
printf(" -f FILE read input from `FILE' (default=stdin)\n\n");
exit(exval);
}
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.
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.
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.
#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:
Compare two strings. Compares the C string str1 to the C string str2. This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached. This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll.
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.
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.
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 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.
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.
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 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.
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.
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.
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).
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.
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).
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.
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.
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).
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,
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.
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 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.
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 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.
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.
This C Program to calculates the volume and surface area of cuboids. The Formula used in this program are surfacerea= 2(w * l + l * h + h * w) where w is Width & l is Length and h is
The goto statement is rarely used because it makes program confusing, less readable and complex. Also, when this is used, the control of the program won't be easy to trace, hence
Read stoplist into binary tree, expects one entry per line. Split string into tokens, return token array. Make sure, copy string to a safe place. Always keep last entry null terminated.
C Program Display the Nodes of a Tree using BFS Traversal. Breadth-first search (BFS) is a strategy for searching in a graph when search is limited to essentially two operations: (a)...
C program code input radius of a circle from user and find diameter, circumference and area of the circle. How to calculate diameter, circumference and area of a circle whose...