第八章:C 库函数
级别 1 — 入门
标准库:C 开箱提供了什么,以及 Auto 如何封装它。
没有 C 程序是孤立运行的。C 标准库提供了 I/O、字符串操作、数学、内存管理和系统交互的基本函数。Auto 将大多数函数封装在更安全、更易用的接口中,同时保留了底层的 C 实现。
8.1 一般属性
C 标准库按头文件组织,每个头文件声明一组相关的函数、类型和宏:
| 头文件 | 用途 | 主要函数 |
|---|---|---|
<stdio.h> | 输入/输出 | printf, scanf, fopen |
<stdlib.h> | 通用工具 | malloc, free, exit, abs |
<string.h> | 字符串处理 | strlen, strcmp, strcpy |
<math.h> | 数学运算 | sqrt, sin, pow, ceil |
<time.h> | 日期和时间 | time, clock, strftime |
<ctype.h> | 字符分类 | isdigit, toupper |
<assert.h> | 诊断 | assert |
<errno.h> | 错误指示器 | errno, strerror |
<stddef.h> | 通用定义 | size_t, NULL, offsetof |
要使用库函数,需要 #include 其头文件:
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>Auto 隐式包含转译后的等价内容。你不需要直接写 #include——a2c 转译器根据代码使用的函数添加必要的头文件。
用 errno 处理错误: 许多 C 库函数通过设置全局变量 errno 并返回哨兵值(通常是 NULL 或 -1)来报告错误。
c
// C:检查 errno
errno = 0;
double result = sqrt(-1.0);
if (errno != 0) {
fprintf(stderr, "Error: %s\n", strerror(errno));
}Auto 将这些模式封装到强制错误检查的返回类型中(如可选类型 ?T 或结果类型 Result<T, E>),消除了忘记检查 errno 的风险。
要点: 在 C 中,始终检查库调用的返回值和
errno。在 Auto 中,类型系统强制你处理错误。
8.2 整数算术
<stdlib.h> 头文件提供整数算术工具:
c
// C
int absolute = abs(-42); // 42
div_t result = div(17, 5); // result.quot = 3, result.rem = 2Auto 通过内置运算符和库函数提供这些功能:
auto
let quotient int = 17 / 5 // 3
let remainder int = 17 % 5 // 2
let absolute int = abs(-42) // 42