Happy Codings - Programming Code Examples

C Programming Code Examples

C > Gnu-Linux Code Examples

Convert a UTC time value

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
/* Convert a UTC time value */ #include <stdio.h> #include <time.h> #include <stdlib.h> int main(int argc, char *argv[]) { struct tm *tm_ptr; time_t the_time; if(argc == 2) the_time = atoi(argv[1]); else (void)time(&the_time); tm_ptr = gmtime(&the_time); printf("raw `UTC' : %ld\n", the_time); printf("ctime : %s", ctime(&the_time)); printf("gmtime : %02d:%02d:%02d - %02d/%02d/%02d\n", tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec, tm_ptr->tm_year - 100, tm_ptr->tm_mon + 1, tm_ptr->tm_mday); return 0; }
If Else Statement in C
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
Syntax for if-else Statement in C
if (test expression) { // run code if test expression is true } else { // run code if test expression is false }
If the test expression is evaluated to true, • statements inside the body of if are executed. • statements inside the body of else are skipped from execution. If the test expression is evaluated to false, • statements inside the body of else are executed • statements inside the body of if are skipped from execution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* if else statement in C language */ // Check whether an integer is odd or even #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); // True if the remainder is 0 if (number%2 == 0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); } return 0; }
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; }
ctime() Function in C
Convert time_t value to string. Interprets the value pointed by timer as a calendar time and converts it to a C-string containing a human-readable version of the corresponding time and date, in terms of local time. The returned string has the following format: Www Mmm dd hh:mm:ss yyyy Where Www is the weekday, Mmm the month (in letters), dd the day of the month, hh:mm:ss the time, and yyyy the year. The string is followed by a new-line character ('\n') and terminated with a null-character. This function is equivalent to: asctime(localtime(timer)) The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer. The returned string has the following format: Www Mmm dd hh:mm:ss yyyy, where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year. The ctime() function is define in the time.h header file. The ctime() function returns the string representing the localtime based on the argument timer.
Syntax for ctime() Function in C
#include <time.h> char *ctime(const time_t *timer)
timer
Pointer to an object of type time_t that contains a time value. time_t is an alias of a fundamental arithmetic type capable of representing times as returned by function time. A C-string containing the date and time information in a human-readable format. The returned value points to an internal array whose validity or value may be altered by any subsequent call to asctime or ctime.
Www
Day of week
Mmm
Month name
dd
Day of month
hh
Hour digit
mm
Minute digit
ss
Second digit
yyyy
Year digit
Data races
The function accesses the object pointed by timer. The function also accesses and modifies a shared internal buffer, which may cause data races on concurrent calls to asctime or ctime. Some libraries provide an alternative function that avoids this data race: ctime_r (non-portable).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* get the string representing the localtime based on the argument timer by ctime() function example */ #include <stdio.h> /* printf */ #include <time.h> /* time_t, time, ctime */ int main () { time_t rawtime; time (&rawtime); printf ("The current local time is: %s", ctime (&rawtime)); time (&rawtime); printf ("The current local time is: %s", ctime (&rawtime)); time (&rawtime); printf ("The current local time is: %s", ctime (&rawtime)); 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; }
gmtime() Function in C
Convert time_t to tm as UTC time. Uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed as a UTC time (i.e., the time at the GMT timezone). The gmtime() function returns a pointer to the broken-down form of time in the form of a tm structure. The time is represented in Coordinated Universal Time (UTC), which is essentially Greenwich mean time. The time pointer is usually obtained through a call to time(). If the system does not support Coordinated Universal Time, NULL is returned. The structure used by gmtime() to hold the broken-down time is statically allocated and is overwritten each time the function is called. If you wish to save the contents of the structure, you must copy it elsewhere.
Syntax for gmtime() Function in C
#include <time.h> struct tm * gmtime (const time_t * timer);
timer
Pointer to an object of type time_t that contains a time value. time_t is an alias of a fundamental arithmetic type capable of representing times as returned by function time. Function returns a pointer to a tm structure with its members filled with the values that correspond to the UTC time representation of timer. The returned value points to an internal object whose validity or value may be altered by any subsequent call to gmtime or localtime. Following is the tm structure information:
struct tm { int tm_sec; /* seconds, range 0 to 59 */ int tm_min; /* minutes, range 0 to 59 */ int tm_hour; /* hours, range 0 to 23 */ int tm_mday; /* day of the month, range 1 to 31 */ int tm_mon; /* month, range 0 to 11 */ int tm_year; /* The number of years since 1900 */ int tm_wday; /* day of the week, range 0 to 6 */ int tm_yday; /* day in the year, range 0 to 365 */ int tm_isdst; /* daylight saving time */ };
Data races
The function accesses the object pointed by timer. The function also accesses and modifies a shared internal object, which may introduce data races on concurrent calls to gmtime and localtime. Some libraries provide an alternative function that avoids this data race: gmtime_r (non-portable).
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
/* convert a calendar time (pointed to by timer) and return a pointer to a structure containing a UTC by gmtime() function code example. */ /* program to illustrate the gmtime() function */ #include <stdio.h> #include <time.h> #define PDT (-7) int main(int argc, const char * argv[]) { /* Define temporary variables */ struct tm *gtime; time_t now; /* Read the current system time */ time(&now); /* Convert the system time to GMT (now UTC) */ gtime = gmtime(&now); /* Display the time in PDT and UTC */ printf ("Pacific Daylight Time: %2d:%02d\n", (gtime->tm_hour + PDT) % 24, gtime->tm_min); printf ("Universal Time: %2d:%02d\n", gtime->tm_hour % 24, gtime->tm_min); return 0; }
time() Function in C
The time() function is defined in time.h header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.
Syntax for time() Function in C
#include <time.h> time_t time( time_t *second )
second
This function accepts single parameter second. This parameter is used to set the time_t object which store the time. This function returns current calender time as a object of type time_t. It is used to get current system time as structure. time() function is a useful utility function that we can use to measure the elapsed time of our program.
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
/* return the time since 00:00:00 UTC, January 1, 1970 by time() function example */ #include <time.h> #include <stdlib.h> #include <stdio.h> int main(void) { time_t current_time; char* c_time_string; /* Obtain current time. */ current_time = time(NULL); if (current_time == ((time_t)-1)) { (void) fprintf(stderr, "Failure to obtain the current time.\n"); exit(EXIT_FAILURE); } /* Convert to local time format. */ c_time_string = ctime(¤t_time); if (c_time_string == NULL) { (void) fprintf(stderr, "Failure to convert the current time.\n"); exit(EXIT_FAILURE); } /* Print to stdout. ctime() has already added a terminating newline character. */ (void) printf("Current time is %s", c_time_string); exit(EXIT_SUCCESS); }
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; }
atoi() Function in C
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 string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.
Syntax for atoi() Function in C
#include <stdlib.h> int atoi (const char * str);
str
C-string beginning with the representation of an integral number. The atoi() function converts a string of characters representing a numeral into a number of int. Similarly, atol() returns a long integer, and in C99, the atoll() function converts a string into an integer of type long long. The conversion ignores any leading whitespace characters (spaces, tabs, newlines). A leading plus sign is permissible; a minus sign makes the return value negative. Any character that cannot be interpreted as part of an integer, such as a decimal point or exponent sign, has the effect of terminating the numeral input, so that atoi() converts only the partial string to the left of that character. If under these conditions the string still does not appear to represent a numeral, then atoi() returns 0. On success, the function returns the converted integral number as an int value. If the converted value would be out of the range of representable values by an int, it causes undefined behavior. See strtol for a more robust cross-platform alternative when this is a possibility.
Data races
The array pointed by str is accessed.
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
/* convert string to integer by atoi() function example */ #include <stdio.h> // Iterative function to implement `atoi()` function in C long atoi(const char* S) { long num = 0; int i = 0; // run till the end of the string is reached, or the // current character is non-numeric while (S[i] && (S[i] >= '0' && S[i] <= '9')) { num = num * 10 + (S[i] - '0'); i++; } return num; } // Implement `atoi()` function in C int main(void) { char S[] = "12345"; printf("%ld ", atoi(S)); return 0; }


C structure is collection of elements of the different data types. Size of the structure can be evaluated using "sizeof operator". Sizeof is operator not function. Sizeof operator takes
C Program Code we generally assume that if a year number is evenly divisible by 4 is leap year. But it is not the only case. A year is a leap year if it is evenly divisible by 100. If it is
Check a files attributes. Check if the file can be written to. File cannot be written. File can be written to. Check if file can be read. File cannot be read. File can be read. Check if...
This C code will calculate the power in watts when you input the voltage and current. Get the voltage. Enter the voltage in volts. Get the current. Enter current in amps. Calculate