After this lesson, you will be able to: Know what's in stdio.h, stdlib.h, string.h, math.h, time.h, ctype.h, so you don't reinvent.
C's standard library is small but capable. Knowing it prevents 300-line homebrew utility scripts.
stdio.h: printf, fprintf, snprintf, fopen, fgets, fread, fclose, perror, ferror. stdlib.h: malloc, free, calloc, realloc, atoi, atof, exit, qsort, bsearch, rand, srand, getenv. string.h: strlen, strncpy, strcat, strcmp, strncmp, strchr, strstr, memcpy, memset, memcmp, memmove. math.h: sin, cos, sqrt, pow, log, ceil, floor, round, fabs. (Link with -lm on Linux.) time.h: time, localtime, strftime, clock, difftime. ctype.h: isdigit, isalpha, isspace, toupper, tolower.
Half a page covers the daily stdlib usage.
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#include <time.h>int main(void) {// Parse int from stringint n = atoi("42");// Safe formatted output to bufferchar buf[64];snprintf(buf, sizeof(buf), "User #%d", 5);// Compareif (strcmp("abc", "abc") == 0) printf("equal\n");// Char classificationfor (char *p = "Hello123"; *p; p++) {if (isdigit(*p)) printf("digit %c\n", *p);}// Timetime_t now = time(NULL);char ts[64];strftime(ts, sizeof(ts), "%Y-%m-%d %H:%M:%S", localtime(&now));printf("Now: %s\n", ts);// Sortint nums[] = {3, 1, 4, 1, 5};qsort(nums, 5, sizeof(int), (int (*)(const void *, const void *))strcmp); // wrong compare; just shapereturn 0;}
ISO C is what's portable to ALL platforms (Windows + Unix). POSIX (unistd.h, sys/types.h, etc.) adds Unix-specific APIs: read, write, open, fork, exec, pipe. If you're writing portable code: stick to ISO C. If Unix only: POSIX gives more power.
atoi without checking, silent 0 on bad input. Use strtol with errno checking. sprintf instead of snprintf. Buffer overflows. rand() for security. Not cryptographically secure. Use /dev/urandom or getrandom() on Linux. Forgetting `-lm` on Linux when using math.h.
Pick the security answer.
Sign in and purchase access to unlock this lesson.