Happy Codings - Programming Code Examples

C Programming Code Examples

C > C on Unix Code Examples

implementation of LN command using system calls

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
/* implementation of LN command using system calls */ #include<stdio.h> #include<fcntl.h> #include<unistd.h> #include<sys/stat.h> int main(int argc,char* argv[]) { int i; struct stat s; if (argc<3) { perror("ERROR:Too Few Arguments"); exit(1); } if(argc>4) { perror("ERROR:Too Many Arguments"); exit(1); } if(argc==3) i=0; else i=1; if(i && !(strcmp(argv[1],"-s")==0)) { perror("ERROR:Invalid Syntax"); exit(1); } if(access(argv[i+1],F_OK)) { perror("ERROR:File name not Found"); exit(1); } if(!access(argv[i+2],F_OK)) { perror("ERROR:File Name already exist"); exit(1); } if(stat(argv[i+1],&s)<0) { perror("ERROR:Unable to reterive stat information"); exit(1); } if(!S_ISREG(s.st_mode)) { perror("ERROR:Not a Regular File"); exit(1); } if(argc==3) if(link(argv[i+1],argv[i+2])<0) { perror("ERROR:Unable to create the Link"); exit(1); } if(argc==4) if(symlink(argv[i+1],argv[i+2])<0) { perror("ERROR:Unable to create the Link"); exit(1); } }
#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; }
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(); }
symlink() Function in C
Create a symbolic link to a path name. Creates the symbolic link named by slink with the file specified by pathname. File access checking is not performed on the file pathname, and the file need not exist. In addition, a symbolic link can cross file system boundaries. If the symlink() function is unsuccessful, any file named by slink is unaffected.
Syntax for symlink() Function in C
#include <unistd.h> int symlink(const char *pathname, const char *slink);
pathname
The path that you want to link to.
slink
The symbolic link that you want to create. If successful, symlink() returns 0. A symbolic link path name is resolved in this fashion: • When a component of a path name refers to a symbolic link rather than to a directory, the path name contained in the symbolic link is resolved. • If the path name in the symbolic link begins with / (slash), the symbolic link path name is resolved relative to the process root directory. • If the path name in the symbolic link does not start with / (slash), the symbolic link path name is resolved relative to the directory that contains the symbolic link. • If the symbolic link is the last component of a path name, it may or may not be resolved. Resolution depends on the function using the path name. For example, rename() does not resolve a symbolic link when it appears as the final component of either the new or old path name. However, open does resolve a symbolic link when it appears as the last component. • If the symbolic link is not the last component of the original path name, remaining components of the original path name are resolved relative to the symbolic link. • When a / (slash) is the last component of a path name and it is preceded by a symbolic link, the symbolic link is always resolved. Because the mode of a symbolic link cannot be changed, its mode is ignored during the lookup process. Any files and directories to which a symbolic link refers are checked for access permission. If unsuccessful, symlink() returns -1, does not affect any file it names, and sets errno to one of the following values:
EACCES
A component of the slink path prefix denies search permission, or write permission is denied in the parent directory of the symbolic link to be created.
EEXIST
The file named by slink already exists.
EINVAL
There is a NULL character in pathname.
EIO
Added for XPG4.2: An I/O error occurred while reading from the file system.
ELOOP
A loop exists in symbolic links. This error is issued if more than POSIX_SYMLOOP symbolic links are encountered during resolution of the slink argument.
ENAMETOOLONG
pathname is longer than PATH_MAX characters, or some component of pathname is longer than NAME_MAX characters while _POSIX_NO_TRUNC is in effect. For symbolic links, the length of the path name string substituted for a symbolic link exceeds PATH_MAX. The PATH_MAX and NAME_MAX values can be determined with pathconf().
ENOENT
Added for XPG4.2: A component of slink does not name an existing file or slink is an empty string. This might be also returned for the following reason: slink has a slash as its last component, which indicates that the preceding component is a directory. A symbolic link cannot be a directory.
ENOSPC
The new symbolic link cannot be created because there is no space left on the file system that will contain the symbolic link.
ENOTDIR
A component of the path prefix of slink is not a directory.
EROFS
The file slink cannot reside on a read-only system.
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
/* make a symbolic link to a file by symlink() function code example */ /* This example works only under z/OS XL C, not z/OS XL C++ */ #define _POSIX1_SOURCE 2 #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> main() { char fn[]="test.file"; char sln[]="test.symlink"; int fd; if ((fd = creat(fn, S_IWUSR)) < 0) perror("creat() error"); else { close(fd); puts("before symlink()"); system("ls -il test.*"); if (symlink(fn, sln) != 0) { perror("symlink() error"); unlink(fn); } else { puts("after symlink()"); system("ls -il test.*"); unlink(fn); puts("after first unlink()"); system("ls -il test.*"); unlink(sln); } } }
main() Function in C
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed. Its first function or entry point of the program from where program start executed, program's execution starts from the main. So main is an important function in c , c++ programming language.
Syntax for main() Function in C
void main() { ......... // codes start from here ......... }
void
is a keyword in C language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value. In place of void we can also use int return type of main() function, at that time main() return integer type value.
main
is a name of function which is predefined function in C library. • An operating system always calls the main() function when a programmers or users execute their programming code. • It is responsible for starting and ends of the program. • It is a universally accepted keyword in programming language and cannot change its meaning and name. • A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program. • A main() function is used to invoke the programming code at the run time, not at the compile time of a program. • A main() function is followed by opening and closing parenthesis brackets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* basic c program by main() function example */ #include <stdio.h> #include <conio.h> main() { printf (" It is a main() function "); int fun2(); // jump to void fun1() function printf ("\n Finally exit from the main() function. "); } void fun1() { printf (" It is a second function. "); printf (" Exit from the void fun1() function. "); } int fun2() { void fun1(); // jump to the int fun1() function printf (" It is a third function. "); printf (" Exit from the int fun2() function. "); return 0; }
perror() Function in C
Print error message. Interprets the value of errno as an error message, and prints it to stderr (the standard error output stream, usually the console), optionally preceding it with the custom message specified in str. errno is an integral variable whose value describes the error condition or diagnostic information produced by a call to a library function (any function of the C standard library may set a value for errno, even if not explicitly specified in this reference, and even if no error happened), see errno for more info.
Syntax for perror() Function in C
#include <stdio.h> void perror ( const char * str );
str
C string containing a custom message to be printed before the error message itself. If it is a null pointer, no preceding custom message is printed, but the error message is still printed. By convention, the name of the application itself is generally used as parameter. This function does not return any value. The error message produced by perror is platform-depend. If the parameter str is not a null pointer, str is printed followed by a colon (:) and a space. Then, whether str was a null pointer or not, the generated error description is printed followed by a newline character ('\n'). perror should be called right after the error was produced, otherwise it can be overwritten by calls to other functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/* print an error message corresponding to the value of errno with perror() function code example */ /* error handling with perror() function and errno */ #include <stdio.h> #include <stdlib.h> #include <errno.h> main() { FILE *fp; char filename[80]; printf("Enter filename: "); gets(filename); if (( fp = fopen(filename, "r")) == NULL) { perror("You goofed!"); printf("errno = %d.\n", errno); exit(1); } else { puts("File opened for reading."); fclose(fp); } return(0); }
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" ); } }
access() Function in C
Determine accessibility of a file. Determines how an HFS file can be accessed. When checking to see if a process has appropriate permissions, access() looks at the real user ID (UID) and group ID (GID), not the effective IDs.
Syntax for access() Function in C
#include <unistd.h> int access(const char *pathname, int how);
pathname
pathname is the name of the file whose accessibility you want to test.
how
The how argument indicates the access modes you want to test. The following symbols are defined in the unistd.h header file for use in the how argument: F_OK: Tests whether the file exists. R_OK: Tests whether the file can be accessed for reading. W_OK: Tests whether the file can be accessed for writing. X_OK: Tests whether the file can be accessed for execution. You can take the bitwise inclusive-OR of any or all of the last three symbols to test several access modes at once. If you are using F_OK to test for the file's existence, you cannot use OR with any of the other symbols. If the specified access is permitted, access() returns 0. If the given file cannot be accessed in the specified way, access() returns -1 and sets errno to one of the following values:
EACCES
The process does not have appropriate permissions to access the file in the specified way, or does not have search permission on some component of the pathname prefix.
EINVAL
The value of how is incorrect.
ELOOP
A loop exists in the symbolic links.
ENAMETOOLONG
pathname is longer than PATH_MAX characters. The PATH_MAX value is determined using pathconf().
ENOENT
There is no file named pathname, or the pathname argument is an empty string.
ENOTDIR
Some component of the pathname prefix is not a directory.
EROFS
The argument how has specified write access for a file on a read-only file system.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* determine accessibility of a file by access() function code example */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main( int argc, char **argv ) { if( argc!= 2 ) { fprintf( stderr, "use: readable <filename>\n" ); return EXIT_FAILURE; } if( !access( argv[1], R_OK ) ) { printf( "ok to read %s\n", argv[1] ); return EXIT_SUCCESS; } else { perror( argv[1] ); return EXIT_FAILURE; } }
strcmp() Function in C
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.
Syntax for strcmp() Function in C
#include <string.h> int strcmp ( const char * str1, const char * str2 );
str1
C string to be compared.
str2
C string to be compared. Function returns an integral value indicating the relationship between the strings: • <0 the first character that does not match has a lower value in ptr1 than in ptr2 • 0 the contents of both strings are equal • >0 the first character that does not match has a greater value in ptr1 than in ptr2 The strcmp() function is used to compare two strings two strings str1 and str2. If two strings are same then strcmp() returns 0, otherwise, it returns a non-zero value. This function compares strings character by character using ASCII value of the characters. The comparison stops when either end of the string is reached or corresponding characters are not same. The non-zero value returned on mismatch is the difference of the ASCII values of the non-matching characters of two strings.
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
/* compare two strings and return an integer value based on the result by strcmp() function example. */ #include <stdio.h> #include <string.h> int main () { char str1[15]; char str2[15]; int ret; strcpy(str1, "abcdef"); strcpy(str2, "ABCDEF"); ret = strcmp(str1, str2); if(ret < 0) { printf("str1 is less than str2"); } else if(ret > 0) { printf("str2 is less than str1"); } else { printf("str1 is equal to str2"); } return(0); }


C language program take the number of days as input. For the number of years, divide the input by 365 and obtain its quotient. For the number of weeks, divide the input by 365 and
Program to input any number from user and check whether nth bit of the given number is set (1) or not (0). How to check whether nth bit of a given number is set or unset using...
C program code to input two numbers and find maximum between two numbers using conditional/ternary operator ?:. How to find maximum minimum between two numbers