9) Standard C library functions and headers
The Standard C Library is a collection of functions and macros that provide essential functionalities to C programs. These functions are specified in the C standard and are available across different platforms. They cover a wide range of operations, including input/output, string manipulation, memory management, mathematics, and more.
Let’s explore some common Standard C Library functions and headers with explanations and examples:
Table of Contents
<stdio.h> Header
The <stdio.h> header provides functions for input and output operations.
Example: Using <stdio.h>
Functions
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
Output:
Enter an integer: 42
You entered: 42
In this example, the printf
function is used to display output, and the scanf
function is used to read input from the user.
Important functions in stdio.h
printf
: Print formatted output to the standard output (console).scanf
: Read formatted input from the standard input (keyboard).puts
: Write a string to the standard output followed by a newline.gets
: Read a line from the standard input (deprecated due to security issues).fgets
: Read a line from a file or stream.fputs
: Write a string to a file or stream.fprintf
: Print formatted output to a file or stream.fscanf
: Read formatted input from a file or stream.fopen
: Open a file for reading or writing.fclose
: Close a file.feof
: Check if the end of a file has been reached.fseek
: Move the file pointer to a specified position.ftell
: Get the current file pointer position.rewind
: Move the file pointer to the beginning of a file.remove
: Delete a file.rename
: Rename a file.perror
: Print an error message based on the value oferrno
.clearerr
: Clear the end-of-file and error indicators for a file.getc
: Read a character from a file or stream.putc
: Write a character to a file or stream.ungetc
: Push a character back into a file or stream.setvbuf
: Set the buffering mode for a file or stream.tmpfile
: Create a temporary file.fread
: Read data from a file or stream.fwrite
: Write data to a file or stream.ferror
: Check if an error has occurred on a file or stream.getchar
: Read a character from the standard input.putchar
: Write a character to the standard output.getchar
: Read a character from the standard input.getchar
: Write a character to the standard output.
<string.h> Header
The <string.h> header provides functions for string manipulation.
Example: Using <string.h>
Functions
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, ";
char str2[] = "world!";
strcat(str1, str2); // Concatenate str2 to str1
printf("Concatenated string: %s\n", str1);
return 0;
}
Output:
Concatenated string: Hello, world!
In this example, the strcat
function is used to concatenate str2
to the end of str1
.
Important functions in string.h
strcpy
: Copy one string to another.strncpy
: Copy a specified number of characters from one string to another.strcat
: Concatenate (append) one string to the end of another.strncat
: Concatenate a specified number of characters from one string to another.strcmp
: Compare two strings lexicographically.strncmp
: Compare a specified number of characters of two strings.strlen
: Calculate the length of a string (excluding the null terminator).strchr
: Find the first occurrence of a character in a string.strrchr
: Find the last occurrence of a character in a string.strstr
: Find the first occurrence of a substring in a string.strpbrk
: Find the first occurrence of any character from a set in a string.strspn
: Get the length of the initial substring containing only characters from a set.strcspn
: Get the length of the initial substring containing characters not from a set.strtok
: Tokenize a string into smaller strings (using delimiters).memset
: Fill a block of memory with a specified value.memcpy
: Copy a block of memory from one location to another.memmove
: Safely copy a block of memory, even if source and destination overlap.memcmp
: Compare two blocks of memory.memchr
: Find the first occurrence of a byte in a block of memory.strerror
: Convert an error number to a string describing the error.strtok_r
: Thread-safe version ofstrtok
using a context pointer.
<stdlib.h> Header
The <stdlib.h> header provides functions for memory allocation, conversion, and other utility functions.
Example: Using <stdlib.h>
Functions
#include <stdio.h>
#include <stdlib.h>
int main() {
int num = 42;
char str[] = "12345";
int converted_num = atoi(str); // Convert string to integer
printf("Converted number: %d\n", converted_num + num);
return 0;
}
Output:
Converted number: 12387
In this example, the atoi
function converts the string "12345"
to an integer, which is then added to num
.
Important functions in stdlib.h
- Memory Allocation and Deallocation:
malloc()
: Allocate memory dynamically.calloc()
: Allocate memory for an array and initialize to zero.realloc()
: Reallocate memory for an existing block.free()
: Deallocate memory previously allocated bymalloc
,calloc
, orrealloc
.
- Conversions:
atoi()
,atol()
,atof()
: Convert strings to integers, long integers, and floating-point numbers.itoa()
,ltoa()
,ftoa()
: Convert integers, long integers, and floating-point numbers to strings.rand()
: Generate pseudo-random integer values.srand()
: Seed the random number generator.
- Process Control:
exit()
: Terminate the program.abort()
: Abort the program (terminate abnormally).getenv()
: Get the value of an environment variable.system()
: Execute a shell command.
- String to Number Conversion:
strtol()
,strtoul()
: Convert strings to long integers.strtof()
,strtod()
,strtold()
: Convert strings to floating-point numbers.
- Memory Management and Utilities:
memset()
: Fill a block of memory with a specified value.memcpy()
,memmove()
: Copy memory blocks.memcmp()
: Compare memory blocks.qsort()
: Sort an array using QuickSort algorithm.bsearch()
: Search for an element in a sorted array.
- String Manipulation:
strcpy()
,strncpy()
: Copy strings.strcat()
,strncat()
: Concatenate strings.strcmp()
,strncmp()
: Compare strings.strlen()
: Get the length of a string.strchr()
,strrchr()
: Locate characters in a string.
- Dynamic Allocation and Deallocation:
_Exit()
: Terminate the program without performing cleanup functions (C11 feature).aligned_alloc()
: Allocate memory with a specified alignment (C11 feature).at_quick_exit()
: Register functions to be called at program exit (C11 feature).quick_exit()
: Terminate the program and call registered functions (C11 feature).
- String Manipulation and Search:
strtok()
: Tokenize strings.strspn()
,strcspn()
: Spanning and non-spanning string scans.strstr()
: Locate a substring within a string.
<math.h> Header
The <math.h> header provides mathematical functions.
Example: Using <math.h>
Functions
#include <stdio.h>
#include <math.h>
int main() {
double x = 2.0;
double result = sqrt(x); // Calculate square root
printf("Square root of %.1f: %.2f\n", x, result);
return 0;
}
Output:
Square root of 2.0: 1.41
In this example, the sqrt function from the <math.h> header calculates the square root of x
.
Of course! Let’s explore more examples of Standard C Library functions and headers:
Important functions in math.h
- Trigonometric Functions:
sin(x)
,cos(x)
,tan(x)
: Sine, cosine, and tangent functions.asin(x)
,acos(x)
,atan(x)
: Inverse sine, cosine, and tangent functions.
- Exponential and Logarithmic Functions:
exp(x)
: Exponential function.log(x)
: Natural logarithm (base e) function.log10(x)
: Base 10 logarithm function.pow(x, y)
: Power function (x
raised to the power ofy
).
- Square Root and Cube Root Functions:
sqrt(x)
: Square root function.cbrt(x)
: Cube root function.
- Rounding and Absolute Value Functions:
ceil(x)
: Round up to the nearest integer.floor(x)
: Round down to the nearest integer.fabs(x)
: Absolute value function.
- Trigonometric Hyperbolic Functions:
sinh(x)
,cosh(x)
,tanh(x)
: Hyperbolic sine, cosine, and tangent functions.
- Floating-Point Manipulation Functions:
frexp(x, *exp)
: Decompose a floating-point number into a normalized fraction and an exponent.ldexp(x, exp)
: Computex * 2^exp
.
- Rounding Functions:
round(x)
,lround(x)
,llround(x)
: Round to the nearest integer.trunc(x)
,lrint(x)
,llrint(x)
: Truncate towards zero.
- Error and Gamma Functions:
erf(x)
,erfc(x)
: Error and complementary error functions.tgamma(x)
: Gamma function.
- Constants:
M_PI
: Value of π (pi).M_E
: Value of e (base of the natural logarithm).
<ctype.h> Header
The <ctype.h> header provides functions for character handling, like converting characters to uppercase or lowercase.
Example: Using <ctype.h>
Functions
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = 'A';
if (isupper(ch)) {
printf("%c is an uppercase letter.\n", ch);
} else {
printf("%c is not an uppercase letter.\n", ch);
}
return 0;
}
Output:
A is an uppercase letter.
In this example, the isupper
function from the <ctype.h>
header checks if the character ch
is an uppercase letter.
Important functions in ctype.h
isalpha(int c)
: Checks if the character is an alphabetic character (a-z or A-Z).isdigit(int c)
: Checks if the character is a digit (0-9).isalnum(int c)
: Checks if the character is an alphanumeric character (a-z, A-Z, or 0-9).isupper(int c)
: Checks if the character is an uppercase letter (A-Z).islower(int c)
: Checks if the character is a lowercase letter (a-z).isspace(int c)
: Checks if the character is a whitespace character (space, tab, newline, etc.).ispunct(int c)
: Checks if the character is a punctuation character (e.g., !, ?, .).isprint(int c)
: Checks if the character is a printable character (including space).iscntrl(int c)
: Checks if the character is a control character (non-printable).tolower(int c)
: Converts the character to lowercase (if applicable).toupper(int c)
: Converts the character to uppercase (if applicable).
<time.h> Header
The <ti
me.h>
header provides functions for working with time and date.
Example: Using <time.h>
Functions
#include <stdio.h>
#include <time.h>
int main() {
time_t current_time;
struct tm *time_info;
time(¤t_time);
time_info = localtime(¤t_time);
printf("Current time: %s", asctime(time_info));
return 0;
}
Output:
Current time: Wed Aug 11 15:37:46 2023
In this example, the time
function retrieves the current time, and the localtime
function converts it into a tm
structure. The asctime
function converts the tm
structure to a human-readable string.
Important functions in time.h
time
Function:- Retrieves the current calendar time and stores it in a
time_t
object.
- Retrieves the current calendar time and stores it in a
difftime
Function:- Calculates the difference in seconds between two time values.
ctime
Function:- Converts a
time_t
value to a string representing the local time in the form of a textual representation (e.g., “Wed Aug 11 15:37:46 2023”).
- Converts a
gmtime
Function:- Converts a
time_t
value to astruct tm
representing Coordinated Universal Time (UTC).
- Converts a
localtime
Function:- Converts a
time_t
value to astruct tm
representing the local time.
- Converts a
strftime
Function:- Formats a
struct tm
value into a specified string format.
- Formats a
asctime
Function:- Converts a
struct tm
value to a string representation of the time in the form of a textual representation (similar toctime
).
- Converts a
mktime
Function:- Converts a
struct tm
value to atime_t
value, essentially reversing the process oflocaltime
.
- Converts a
clock
Function:- Returns the number of clock ticks since the program started execution.
difftime
Function:- Calculates the difference between two time values and returns it in seconds.
mktime
Function:- Converts a
struct tm
value to atime_t
value.
- Converts a
strftime
Function:- Formats a
struct tm
value into a specified string format.
- Formats a
<stddef.h> Header
The <stddef.h> header provides macros for defining various standard types.
Example: Using <stddef.h>
Macros
#include <stdio.h>
#include <stddef.h>
int main() {
size_t size = sizeof(int);
printf("Size of int: %zu bytes\n", size);
return 0;
}
Output:
Size of int: 4 bytes
In this example, the sizeof
operator is used to determine the size of the int
data type.
Important functions in stddef.h
1. size_t
: This is an unsigned integer type used to represent sizes of objects in bytes.
2. ptrdiff_t
: This is a signed integer type used to represent the difference between two pointers.
3. NULL
: This macro represents a null pointer, often used to indicate that a pointer is not pointing to any valid memory location.
4. offsetof
: This macro is used to find the offset of a member within a structure.
5. wchar_t
: This is an integer type used for wide character representation, suitable for representing a wide range of characters beyond ASCII.
6. max_align_t
: This type represents the most stringent alignment requirement for any scalar type on the target architecture.
<stdarg.h> Header
The <stdarg.h> header provides functions for handling variable argument lists, useful for functions with a variable number of arguments.
Example: Using <stdarg.h>
Functions
#include <stdio.h>
#include <stdarg.h>
int sum(int count, ...) {
va_list args;
va_start(args, count);
int total = 0;
for (int i = 0; i < count; ++i) {
total += va_arg(args, int);
}
va_end(args);
return total;
}
int main() {
int result = sum(4, 10, 20, 30, 40);
printf("Sum: %d\n", result);
return 0;
}
Output:
Sum: 100
In this example, the sum
function uses the <stdarg.h>
header to handle a variable number of integer arguments.
Important functions in stdarg.h
va_list
:- A type representing the variable argument list.
- Used to declare a variable that holds the variable arguments.
va_start
:- Macro that initializes a
va_list
to point to the first variable argument. - Takes two arguments: the
va_list
variable and the last named parameter before the variable arguments.
- Macro that initializes a
va_arg
:- Macro that retrieves the next argument from the
va_list
. - Takes two arguments: the
va_list
variable and the data type of the next argument.
- Macro that retrieves the next argument from the
va_end
:- Macro that cleans up and invalidates the
va_list
after variable arguments have been processed. - Takes one argument: the
va_list
variable.
- Macro that cleans up and invalidates the
va_copy
:- Macro that copies the state of a
va_list
variable to anotherva_list
. - Useful for reusing the original argument list without modifying it.
- Macro that copies the state of a
These are just a few examples of the Standard C Library functions and headers. The library provides a wide range of functionalities, from file operations to memory management, time and date handling, and more. By including the appropriate headers and using the provided functions, you can enhance the capabilities of your C programs without reinventing the wheel.