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:

<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

  1. printf: Print formatted output to the standard output (console).
  2. scanf: Read formatted input from the standard input (keyboard).
  3. puts: Write a string to the standard output followed by a newline.
  4. gets: Read a line from the standard input (deprecated due to security issues).
  5. fgets: Read a line from a file or stream.
  6. fputs: Write a string to a file or stream.
  7. fprintf: Print formatted output to a file or stream.
  8. fscanf: Read formatted input from a file or stream.
  9. fopen: Open a file for reading or writing.
  10. fclose: Close a file.
  11. feof: Check if the end of a file has been reached.
  12. fseek: Move the file pointer to a specified position.
  13. ftell: Get the current file pointer position.
  14. rewind: Move the file pointer to the beginning of a file.
  15. remove: Delete a file.
  16. rename: Rename a file.
  17. perror: Print an error message based on the value of errno.
  18. clearerr: Clear the end-of-file and error indicators for a file.
  19. getc: Read a character from a file or stream.
  20. putc: Write a character to a file or stream.
  21. ungetc: Push a character back into a file or stream.
  22. setvbuf: Set the buffering mode for a file or stream.
  23. tmpfile: Create a temporary file.
  24. fread: Read data from a file or stream.
  25. fwrite: Write data to a file or stream.
  26. ferror: Check if an error has occurred on a file or stream.
  27. getchar: Read a character from the standard input.
  28. putchar: Write a character to the standard output.
  29. getchar: Read a character from the standard input.
  30. 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

  1. strcpy: Copy one string to another.
  2. strncpy: Copy a specified number of characters from one string to another.
  3. strcat: Concatenate (append) one string to the end of another.
  4. strncat: Concatenate a specified number of characters from one string to another.
  5. strcmp: Compare two strings lexicographically.
  6. strncmp: Compare a specified number of characters of two strings.
  7. strlen: Calculate the length of a string (excluding the null terminator).
  8. strchr: Find the first occurrence of a character in a string.
  9. strrchr: Find the last occurrence of a character in a string.
  10. strstr: Find the first occurrence of a substring in a string.
  11. strpbrk: Find the first occurrence of any character from a set in a string.
  12. strspn: Get the length of the initial substring containing only characters from a set.
  13. strcspn: Get the length of the initial substring containing characters not from a set.
  14. strtok: Tokenize a string into smaller strings (using delimiters).
  15. memset: Fill a block of memory with a specified value.
  16. memcpy: Copy a block of memory from one location to another.
  17. memmove: Safely copy a block of memory, even if source and destination overlap.
  18. memcmp: Compare two blocks of memory.
  19. memchr: Find the first occurrence of a byte in a block of memory.
  20. strerror: Convert an error number to a string describing the error.
  21. strtok_r: Thread-safe version of strtok 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

  1. 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 by malloc, calloc, or realloc.
  2. 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.
  3. 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.
  4. String to Number Conversion:
    • strtol(), strtoul(): Convert strings to long integers.
    • strtof(), strtod(), strtold(): Convert strings to floating-point numbers.
  5. 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.
  6. 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.
  7. 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).
  8. 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

  1. 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.
  2. 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 of y).
  3. Square Root and Cube Root Functions:
    • sqrt(x): Square root function.
    • cbrt(x): Cube root function.
  4. 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.
  5. Trigonometric Hyperbolic Functions:
    • sinh(x), cosh(x), tanh(x): Hyperbolic sine, cosine, and tangent functions.
  6. Floating-Point Manipulation Functions:
    • frexp(x, *exp): Decompose a floating-point number into a normalized fraction and an exponent.
    • ldexp(x, exp): Compute x * 2^exp.
  7. Rounding Functions:
    • round(x), lround(x), llround(x): Round to the nearest integer.
    • trunc(x), lrint(x), llrint(x): Truncate towards zero.
  8. Error and Gamma Functions:
    • erf(x), erfc(x): Error and complementary error functions.
    • tgamma(x): Gamma function.
  9. 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

  1. isalpha(int c): Checks if the character is an alphabetic character (a-z or A-Z).
  2. isdigit(int c): Checks if the character is a digit (0-9).
  3. isalnum(int c): Checks if the character is an alphanumeric character (a-z, A-Z, or 0-9).
  4. isupper(int c): Checks if the character is an uppercase letter (A-Z).
  5. islower(int c): Checks if the character is a lowercase letter (a-z).
  6. isspace(int c): Checks if the character is a whitespace character (space, tab, newline, etc.).
  7. ispunct(int c): Checks if the character is a punctuation character (e.g., !, ?, .).
  8. isprint(int c): Checks if the character is a printable character (including space).
  9. iscntrl(int c): Checks if the character is a control character (non-printable).
  10. tolower(int c): Converts the character to lowercase (if applicable).
  11. toupper(int c): Converts the character to uppercase (if applicable).

<time.h> Header

The <time.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(&current_time);
    time_info = localtime(&current_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

  1. time Function:
    • Retrieves the current calendar time and stores it in a time_t object.
  2. difftime Function:
    • Calculates the difference in seconds between two time values.
  3. 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”).
  4. gmtime Function:
    • Converts a time_t value to a struct tm representing Coordinated Universal Time (UTC).
  5. localtime Function:
    • Converts a time_t value to a struct tm representing the local time.
  6. strftime Function:
    • Formats a struct tm value into a specified string format.
  7. asctime Function:
    • Converts a struct tm value to a string representation of the time in the form of a textual representation (similar to ctime).
  8. mktime Function:
    • Converts a struct tm value to a time_t value, essentially reversing the process of localtime.
  9. clock Function:
    • Returns the number of clock ticks since the program started execution.
  10. difftime Function:
    • Calculates the difference between two time values and returns it in seconds.
  11. mktime Function:
    • Converts a struct tm value to a time_t value.
  12. strftime Function:
    • Formats a struct tm value into a specified string format.

<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

  1. va_list:
    • A type representing the variable argument list.
    • Used to declare a variable that holds the variable arguments.
  2. 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.
  3. 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.
  4. va_end:
    • Macro that cleans up and invalidates the va_list after variable arguments have been processed.
    • Takes one argument: the va_list variable.
  5. va_copy:
    • Macro that copies the state of a va_list variable to another va_list.
    • Useful for reusing the original argument list without modifying it.

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.

Leave a Reply