Skip to content

C 标准库速查

C 标准库只有 20 来个头文件,却覆盖了字符处理、错误报告、类型极限、内存、排序、时间、信号等全部基础设施。这篇按"解决什么问题"把它们分组过一遍,每个头文件给出核心函数、真实用法和库级陷阱。当作参考手册用:写 C 时先来这查有没有轮子,别急着手写。

一、头文件地图

头文件解决什么代表函数/宏
assert.h断言与调试assert、static_assert
ctype.h字符分类与转换isdigit、toupper
errno.h错误码报告errno、ERANGE
float.h浮点极限DBL_MAX、FLT_EPSILON
inttypes.h定宽整型的格式宏PRId64、imaxdiv
iso646.h运算符替代记号and、or、not
limits.h整型极限INT_MAX、CHAR_BIT
locale.h本地化设置setlocale
math.h数学函数sqrt、pow、fabs
setjmp.h非局部跳转setjmp、longjmp
signal.h信号处理signal、raise
stdint.h定宽整型int32_t、uint64_t
stdlib.h通用工具malloc、qsort、strtol
stdarg.h可变参数va_start、va_arg
stddef.h基础定义NULL、size_t、offsetof
stdio.h输入输出printf、fopen、fread
string.h字符串与内存操作strlen、memcpy
time.h时间日期time、clock、strftime
wchar.h宽字符与宽字符串wprintf、wcslen
wctype.h宽字符分类iswalpha

其中 stdio.h(详见《输入输出与文件操作》)、string.h(详见《数组与字符串》)、stdlib.h 的内存函数(详见《内存管理》)、stdarg.h(详见《函数》第五章)在专篇展开,本篇讲其余部分。

二、断言与调试:<assert.h>

c
#include <assert.h>

double average(const int *a, size_t n) {
    assert(a != NULL);        /* 前置条件:程序员错误,不是运行时错误 */
    assert(n > 0);
    return (double)sum(a, n) / n;
}
  • assert(expr):expr 为假时打印文件、行号、表达式并调用 abort();
  • 定义 NDEBUG(gcc -DNDEBUG -O2,发布构建标配)后所有 assert 展开为空——零开销;
  • 断言用于"不可能发生"的程序员错误,不用于用户输入校验:输入错误是预期内的,要返回错误码;断言是契约检查,开发期抓"调用方违约";
  • C11 起 static_assert(条件, 消息) 是编译期断言,检查编译期已知的事实,如 static_assert(sizeof(int) == 4, "...")。

三、字符处理:<ctype.h> 与 <wctype.h>

c
#include <ctype.h>

int isdigit(int c);  int isalpha(int c);  int isalnum(int c);
int isspace(int c);  int isupper(int c);  int islower(int c);
int isxdigit(int c); int toupper(int c);  int tolower(int c);
c
for (char *p = s; *p; p++)
    *p = (char)toupper((unsigned char)*p);   /* 原地转大写 */

两个坑:

  1. 参数必须能表示为 unsigned char 或 EOF。char 有符号时,中文字节(负值)传给 isdigit 是 UB——先转 unsigned char;
  2. toupper 只对 ASCII 可靠,中文、拉丁扩展字符一概不认识。需要 Unicode 级转换的自己建映射表,或用宽字符版 <wctype.h>(iswalpha、towupper,参数是 wint_t)。

四、错误处理:<errno.h>

errno 是一个 lvalue(多线程里是线程局部),库函数失败时把它设为错误码,成功后不清零——所以检查前先手动清零:

c
#include <stdio.h>
#include <errno.h>
#include <string.h>

errno = 0;
long v = strtol(str, &end, 10);
if (errno == ERANGE)
    fprintf(stderr, "数值溢出:%s\n", strerror(errno));

FILE *fp = fopen("no_such_file", "r");
if (fp == NULL) {
    perror("fopen");              /* fopen: No such file or directory */
    return -1;
}

三个组成部分:errno 错误码变量;EDOM/ERANGE/EILSEQ 等标准错误码(ERANGE 最常见:转换或数学函数超出范围);perror(msg) 打印 msg: 错误描述 到 stderr,strerror(errno) 返回错误描述字符串(可拼接进日志)。错误码数字没人记得住,永远用 perror/strerror 转成文字。

五、数值极限:<limits.h> <float.h> <stdint.h> <inttypes.h>

5.1 limits.h——整型极限

c
CHAR_BIT              /* 8:每字节位数 */
SCHAR_MIN/MAX UCHAR_MAX          /* -128/127, 255 */
SHRT_MIN/MAX                    /* -32768/32767 */
INT_MIN/INT_MAX                 /* -2147483648/2147483647 */
LONG_MIN/LONG_MAX
LLONG_MIN/LLONG_MAX             /* C99 */

用途:防溢出判断(if (a > INT_MAX / b) 说明 a*b 会溢出)、可移植性假设、数组维度设计。

5.2 float.h——浮点极限

c
FLT_MAX FLT_MIN DBL_MAX DBL_MIN LDBL_MAX
FLT_EPSILON DBL_EPSILON      /* 1.0 与下一个可表示值的差:浮点比较的 epsilon 基准 */
FLT_DIG DBL_DIG              /* 保证精度的十进制位数:7/15 */

写"浮点相等比较"时 DBL_EPSILON 量级就是误差基准(运算符篇讲过:别 ==,比较差值)。

5.3 stdint.h——定宽整型(C99)

c
int8_t int16_t int32_t int64_t      /* 有符号定宽,保证存在 */
uint8_t uint16_t uint32_t uint64_t  /* 无符号定宽 */
int_leastN_t / uint_leastN_t        /* 至少 N 位(没有恰好 N 位时的退路) */
int_fastN_t / uint_fastN_t          /* 至少 N 位且运算最快 */
intptr_t uintptr_t                  /* 可存指针的整型 */
SIZE_MAX                           /* size_t 的最大值 */
INT64_C(0) UINT32_C(1)             /* 定宽字面量后缀宏 */

二进制协议、文件格式、硬件寄存器、跨平台序列化,一律用定宽类型——int 换个平台可能是 16 位,协议立刻错。字面量用 UINT32_C(1) 而不是裸 1u,保证宽度精确。

5.4 inttypes.h——定宽类型的 printf 格式

int64_t 在某个平台是 long、另一个平台是 long long,%ld 和 %lld 写哪个都不全对。格式宏解决:

c
#include <inttypes.h>
#include <stdio.h>

int64_t big = 9000000000LL;
printf("%" PRId64 "\n", big);        /* 平台自动选对长度修饰符 */
printf("%" PRIu64 " %" PRIx64 "\n", big, big);

uint8_t byte = 0xFF;
printf("%" PRIu8 "\n", byte);        /* 注意:uint8_t 会提升为 int,也可直接 %d */

SCNd64/SCNu32 系列给 scanf 用。跨平台打印整型,这些宏是唯一正确答案。

六、数学函数:<math.h>

c
#include <math.h>

double sqrt(double x);   double pow(double b, double e);
double fabs(double x);   double floor(double x);   double ceil(double x);
double sin/cos/tan(double x);      double log/log10(double x);
double exp(double x);              double fmod(double x, double y);
c
printf("%.2f %.2f\n", sqrt(2.0), pow(2.0, 10));   /* 1.41 1024.00 */
printf("%.0f %.0f\n", floor(3.7), ceil(3.2));     /* 3 4 */
printf("%.1f\n", fmod(10.0, 3.0));                /* 1.0 */

使用要点:

  • 链接要加 -lm(gcc calc.c -o calc -lm),否则 undefined reference to 'sqrt'——这是新手第一个链接错误;
  • 先检查定义域:sqrt(-1) 返回 NaN 并置 errno = EDOM,log(0) 返回 -HUGE_VAL 并置 errno = ERANGE。写库函数式代码时,用 errno 或 isnan()/isinf()(C99 math.h)判断异常返回;
  • 浮点结果不能直接 == 比较(见运算符篇):sqrt(2)*sqrt(2) == 2.0 未必为真;
  • C99 的类型泛化宏(<tgmath.h>):写 sqrt(x),x 是 float 就调 sqrtf,是 double 调 sqrt,是 long double 调 sqrtl——免去记三个后缀。

七、工具函数:<stdlib.h>

标准库的"杂物箱",按用途分组(内存函数见《内存管理》专篇)。

7.1 字符串转数字

c
int atoi(const char *s);                              /* 简单,无错误检测 */
long strtol(const char *s, char **end, int base);     /* 完整错误检测,推荐 */
double strtod(const char *s, char **end);             /* 浮点版 */

strtol 的 base 传 0 时自动识别 0x 前缀(十六进制)、0 前缀(八进制)、否则十进制;end 返回第一个无法解析的字符位置:

c
char *end;
errno = 0;
long v = strtol(argv[1], &end, 10);
if (end == argv[1])        fprintf(stderr, "不是数字\n");
else if (*end != '\0')     fprintf(stderr, "数字后面有垃圾:%s\n", end);
else if (errno == ERANGE)  fprintf(stderr, "溢出\n");

命令行解析数字永远用 strtol 不用 atoi——atoi("abc") 返回 0,和 atoi("0") 无法区分,错误静默通过。

7.2 随机数

c
srand((unsigned)time(NULL));      /* 播种,程序启动时一次 */
int r = rand();                   /* 0 ~ RAND_MAX(至少 32767) */
int d = rand() % 6 + 1;           /* 1~6 骰子 */

rand() 是伪随机(线性同族,可预测),低比特位规律性强——rand() % 2 交替出现是著名缺陷。要质量用平台 API 或 C++ <random>;% 取模有模偏差(RAND_MAX=32767 时 rand()%100 让 0~67 概率略高),多数场景可忽略。

7.3 退出与环境

c
void exit(int status);             /* 立即终止进程:执行 atexit 回调、刷新流 */
void abort(void);                  /* 异常终止(SIGABRT),不做清理 */
int atexit(void (*func)(void));    /* 注册进程退出回调(LIFO) */
char *getenv(const char *name);    /* 读环境变量 */
int system(const char *cmd);       /* 执行 shell 命令(安全慎用) */

static void cleanup(void) { puts("退出前清理"); }
int main(void) {
    atexit(cleanup);
    if (fail) exit(EXIT_FAILURE);  /* 触发回调 */
    return EXIT_SUCCESS;           /* 正常返回也触发 */
}

7.4 查找与排序:qsort / bsearch

c
void qsort(void *base, size_t nmemb, size_t size,
           int (*compar)(const void *, const void *));
void *bsearch(const void *key, const void *base, size_t nmemb, size_t size,
              int (*compar)(const void *, const void *));

int cmp_int(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);          /* 防减法溢出:x-y 在极值处会溢出 */
}

int arr[] = {3, 1, 4, 1, 5};
qsort(arr, 5, sizeof(int), cmp_int);

int key = 4;
int *found = bsearch(&key, arr, 5, sizeof(int), cmp_int);   /* 前提:已排序 */

比较函数返回负数/0/正数表示"小于/等于/大于"。return x - y 是常见错误——INT_MAX - (-1) 溢出,符号错误,排序乱套。bsearch 前数组必须已排序,否则结果无意义。

八、基础定义:<stddef.h>

个头小、地位高:定义了 C 程序员天天用的四个名字。

c
#define NULL ((void *)0)          /* 空指针常量(多数实现) */
typedef ... size_t;               /* sizeof 的返回类型:无符号 */
typedef ... ptrdiff_t;            /* 指针相减的结果类型:有符号 */
#define offsetof(type, member)    /* 成员在结构体中的字节偏移 */

size_t 是无符号的——所以 for (int i = 0; i < n; i++) 和 size_t n 比较时 i 转无符号,负值变天文数字(运算符篇的经典坑)。offsetof 是结构体内存分析的探针:printf("%zu\n", offsetof(struct Sample, i)) 直接验证对齐布局。

九、非局部跳转:<setjmp.h>

c
int setjmp(jmp_buf env);                /* 保存当前执行上下文,首次返回 0 */
void longjmp(jmp_buf env, int status);  /* 跳回 setjmp 处,setjmp 返回 status */

jmp_buf env;
if (setjmp(env) == 0) {
    deep_function(&env);          /* 深层出问题时长跳回来 */
} else {
    handle_error();               /* 错误路径:longjmp 落到这里 */
}

用途:深层嵌套中一步跳回顶层、错误恢复框架的雏形。坑:

  • longjmp 之后,跳过的栈帧里的局部变量值是未定义的(除非声明为 volatile)——栈已被销毁重建;
  • 跳过的函数里分配的内存泄漏,atexit 注册的回调不会执行。

现代 C 里 setjmp 主要存在于历史代码和特定库(如 libpng 的错误处理),新代码优先用错误码或 goto cleanup。

十、信号与中断:<signal.h>

信号是操作系统发给进程的"异步通知"——Ctrl+C、段错误、定时器、kill 命令,都是信号。

c
#include <signal.h>
#include <stdio.h>

volatile sig_atomic_t stop = 0;     /* 标志位:必须 sig_atomic_t + volatile */

void handle_sigint(int sig) {
    stop = 1;                       /* 只做最简单的事:置标志 */
    (void)sig;
}

int main(void) {
    signal(SIGINT, handle_sigint);  /* 注册 Ctrl+C 处理函数 */
    while (!stop) {
        do_work();
    }
    printf("收到中断,优雅退出\n");
    return 0;
}

标准信号:SIGINT(中断)、SIGSEGV(段错误)、SIGABRT(abort)、SIGFPE(算术错误)、SIGTERM(终止请求)、SIGILL(非法指令)。注册方式:signal(sig, handler) 装处理函数、SIG_IGN 忽略、SIG_DFL 恢复默认;raise(SIGINT) 给自己发信号。

sig_atomic_t 保证读写原子(信号处理函数和主程序可能并发访问),volatile 告诉编译器别把它缓存进寄存器——这是信号安全编程的两条铁律。

信号处理的纪律:

  • 处理函数里只做异步安全的事:置标志、写 volatile sig_atomic_t。printf、malloc、free 都不是信号安全的(内部状态可能被中断打断);
  • SIGSEGV 的默认动作是终止进程。可以注册处理函数做临终日志,但之后要么 longjmp 恢复要么 _exit——继续跑一个已经踩坏内存的进程是危险的;
  • POSIX 的 sigaction 比标准 signal 语义更明确(signal 在某些系统上是一次性的),严肃代码用 sigaction。

嵌入式中断:裸机开发里"中断"是硬件事件(定时器、GPIO),由中断向量表跳转到中断服务函数(ISR),与这里的"信号"是不同层面的机制,但设计原则相通——ISR 里也要快进快出,重活儿交给主循环(即上面的"置标志"模式)。

十一、时间日期:<time.h>

c
#include <time.h>

time_t t = time(NULL);            /* 当前 Unix 时间戳(秒,1970-01-01 起) */

/* 计时:clock() 测 CPU 时间,time() 是墙上时钟 */
clock_t start = clock();
do_work();
printf("耗时 %.2f 秒\n", (double)(clock() - start) / CLOCKS_PER_SEC);

/* 格式化 */
struct tm *local = localtime(&t);      /* 转本地时间结构体(静态缓冲区,非线程安全) */
char buf[64];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", local);
printf("现在:%s\n", buf);             /* 现在:2026-10-23 14:30:00 */

常用格式符:%Y 年、%m 月、%d 日、%H 时、%M 分、%S 秒、%j 年内第几天、%A 星期名。反向操作用 POSIX 的 strptime(解析)+ mktime(tm → time_t),差值用 difftime(t2, t1),UTC 用 gmtime。线程安全版本是 localtime_r/gmtime_r(POSIX)。

注意:32 位系统上 time_t 是有符号 32 位,2038 年溢出——现代 64 位系统已无此虑,但嵌入式老代码要当心。

十二、本地化:<locale.h>

c
#include <locale.h>

setlocale(LC_ALL, "");            /* 采用环境变量设定的区域 */
printf("%'.2f\n", 1234567.89);    /* ' 标志:千分位分组(需区域支持) */

类别常量:LC_ALL(全部)、LC_NUMERIC(数字格式)、LC_TIME(日期格式)、LC_COLLATE(排序规则)、LC_CTYPE(字符分类)。C 程序启动时默认是 "C" 区域(ASCII、英文习惯)。它解决的是"数字千分位、日期格式"这类本地化——字符串编码问题(GBK/UTF-8)要靠统一编码解决,setlocale 不是银弹。

十三、替代记号:<iso646.h>

C95 为没有 &&、|| 等符号的老键盘提供的宏,包含即得:and(&&)、or(||)、not(!)、bitand(&)、bitor(|)、xor(^)、compl(~)、and_eq(&=)、not_eq(!=)。现代键盘都有这些符号,它的价值主要是读老代码时认得。

十四、宽字符与多字节:<wchar.h>

c
#include <wchar.h>

wchar_t wc = L'中';              /* 宽字符字面量 */
wchar_t ws[] = L"中文字符串";

wprintf(L"%ls\n", ws);           /* 宽字符 printf */
size_t len = wcslen(ws);         /* 宽字符串长度(字符数,非字节数) */

mbstowcs(wbuf, "hello", 64);     /* 多字节 → 宽字符 */
wcstombs(cbuf, wbuf, 64);        /* 宽字符 → 多字节 */

关键认知:wchar_t 的宽度平台相关(Linux 4 字节 UTF-32,Windows 2 字节 UTF-16),宽字符代码同样不可移植。跨平台文本的现代答案是 UTF-8 字节流 + 按需解码(详见《数组与字符串》多字节章节)。配套的宽字符分类在 <wctype.h>(iswalpha、towupper)。

十五、高频函数速查表

需求函数头文件
打印/读取printf scanf fgets fprintfstdio.h
文件操作fopen fclose fread fwrite fseekstdio.h
字符串操作strlen strncpy strcmp strtokstring.h
内存块操作memcpy memmove memsetstring.h
动态内存malloc calloc realloc freestdlib.h
数字解析strtol strtod(不用 atoi)stdlib.h
随机数rand srandstdlib.h
排序/查找qsort bsearchstdlib.h
进程退出exit atexit abortstdlib.h
断言assert static_assertassert.h
字符判断isdigit isspace toupperctype.h
错误报告errno perror strerrorerrno.h/string.h
整型极限INT_MAX SIZE_MAXlimits.h/stdint.h
定宽类型int32_t uint64_t PRId64stdint.h/inttypes.h
数学sqrt pow fabs floor ceilmath.h
可变参数va_start va_arg va_endstdarg.h
信号signal raise sig_atomic_tsignal.h
非局部跳转setjmp longjmpsetjmp.h
时间time clock localtime strftimetime.h
宽字符wprintf wcslen mbstowcswchar.h

十六、常见库级陷阱速查

坑后果规避
atoi 解析失败返回 0错误静默通过strtol + errno/end 检查
isdigit(c) 传负数字节UB转 unsigned char
比较函数 return x - y极值处溢出,排序错误(x>y)-(x<y)
localtime 返回静态指针非线程安全、下次调用被覆盖localtime_r
用 errno 不先清零读到上一次调用的错误码调用前 errno = 0
信号处理函数里 printf非异步安全,可能死锁只置 volatile sig_atomic_t
printf 格式与类型不符UB开 -Wformat
用 math.h 不链 -lmundefined reference to 'sqrt'编译加 -lm

十七、自检清单

  • [ ] 说得出 20 个头文件各自解决什么问题,需要时知道去哪查
  • [ ] 会用 strtol 写带完整错误检测的数字解析
  • [ ] 默写 qsort + 比较函数的正确写法(含防溢出返回)
  • [ ] 解释 assert 与用户输入校验的分工、NDEBUG 的作用
  • [ ] 写得出带 SIGINT 处理的优雅退出程序,并说明信号安全纪律

CTO Plus技术栈 Version 1.0.20261024-12