概述
本文匯總 C 標準庫主要頭文件的核心功能、常用函數、宏與類型,供快速查閱。
<assert.h> - 斷言
assert(expr):expr 為 0 時輸出錯誤並調用 abort() 終止程序。
- 定義
NDEBUG 可禁用所有斷言。
<ctype.h> - 字符分類與轉換
所有函數接收 int(實為 unsigned char 或 EOF),返回 int。
| 函數 | 功能 |
isalnum(c) | 字母或數字 |
isalpha(c) | 字母 |
isdigit(c) | 數字 0-9 |
islower(c) | 小寫字母 |
isupper(c) | 大寫字母 |
isspace(c) | 空白字符 |
isxdigit(c) | 十六進制數字 |
tolower(c) | 轉小寫 |
toupper(c) | 轉大寫 |
<errno.h> - 錯誤碼
errno:線程局部變量,記錄最近一次庫函數錯誤碼。
- 常見宏:
EDOM(參數域錯誤)、ERANGE(結果範圍錯誤)、EILSEQ(非法字節序列)。
<float.h> - 浮點數特性
定義 float/double/long double 的範圍與精度宏:
FLT_DIG、DBL_DIG、LDBL_DIG:十進制精度位數
FLT_MAX、DBL_MAX、LDBL_MAX:最大值
FLT_EPSILON 等:最小可表示差值
<limits.h> - 整型範圍
CHAR_BIT:位/字節
INT_MIN、INT_MAX、UINT_MAX 等
LONG_MIN、LONG_MAX、ULONG_MAX
<locale.h> - 本地化
setlocale(category, locale):設置/查詢區域設置
localeconv():返回 lconv 結構,含貨幣、數字格式信息
- 類別:
LC_ALL、LC_CTYPE、LC_NUMERIC、LC_TIME 等
<math.h> - 數學函數
| 分類 | 函數示例 |
| 三角 | sin cos tan asin acos atan atan2 |
| 雙曲 | sinh cosh tanh |
| 指數對數 | exp log log10 pow sqrt |
| 取整 | ceil floor fmod modf frexp ldexp |
<setjmp.h> - 非局部跳轉
setjmp(jmp_buf):保存上下文,首次返回 0
longjmp(jmp_buf, val):跳回 setjmp 處,使其返回 val
- 用於深層嵌套錯誤恢復、協程雛形
<signal.h> - 信號處理
- 信號宏:
SIGINT、SIGSEGV、SIGFPE、SIGTERM 等
signal(sig, handler):註冊處理函數,SIG_DFL 默認、SIG_IGN 忽略
raise(sig):發送信號給自身
<stdarg.h> - 可變參數
va_list、va_start(ap, last)、va_arg(ap, type)、va_end(ap)
- 實現
printf 類函數的基礎
<stddef.h> - 通用定義
NULL、size_t、ptrdiff_t、wchar_t
offsetof(type, member):成員偏移量
<stdio.h> - 輸入輸出
核心類型:FILE*、size_t、fpos_t
核心宏:EOF、BUFSIZ、FILENAME_MAX、SEEK_SET/CUR/END
核心流:stdin、stdout、stderr
| 分類 | 函數 |
| 文件操作 | fopen fclose freopen remove rename tmpfile tmpnam |
| 格式化IO | printf/scanf fprintf/fscanf sprintf/sscanf vprintf 族 |
| 字符IO | fgetc/fputc getc/putc getchar/putchar fgets/fputs gets/puts ungetc |
| 二進制IO | fread/fwrite |
| 定位 | fseek/ftell fgetpos/fsetpos rewind |
| 緩衝 | setbuf/setvbuf fflush |
| 錯誤 | ferror/feof/clearerr/perror |
<stdlib.h> - 實用工具
| 分類 | 函數/宏 |
| 轉換 | atoi/atol/atof strtol/strtod/strtoul |
| 內存 | malloc/calloc/realloc/free aligned_alloc(C17) |
| 程序控制 | abort/exit/atexit/quick_exit system/getenv |
| 排序搜索 | qsort/bsearch |
| 數學 | abs/labs/llabs div/ldiv/lldiv |
| 隨機 | rand/srand |
| 多字節 | mblen/mbtowc/wctomb/mbstowcs/wcstombs |
<string.h> - 字符串與內存
| 分類 | 函數 |
| 複製 | strcpy/strncpy memcpy/memmove |
| 連接 | strcat/strncat |
| 比較 | strcmp/strncmp memcmp strcoll/strxfrm |
| 查找 | strchr/strrchr strstr strpbrk memchr |
| 長度 | strlen |
| 其他 | memset strerror strtok strspn/strcspn |
<time.h> - 時間日期
- 類型:
time_t、clock_t、struct tm
- 函數:
time、clock、difftime、mktime、localtime/gmtime、asctime/ctime、strftime
- 宏:
CLOCKS_PER_SEC
使用建議
- 優先使用標準庫函數,避免重複造輪子。
- 注意函數的線程安全性(如
strtok 非線程安全,用 strtok_r)。
- 檢查返回值與
errno 進行錯誤處理。
- 內存分配後必須檢查
NULL,使用後及時 free。