标准库 stdio.h、stdlib.h、string.h 高阶用法
·
一、stdio.h 高阶用法
1. sprintf /sscanf 字符串格式化神器
c
运行
// 数字转字符串
char buf[20];
int a = 123;
sprintf(buf, "%d", a);
// 字符串拆分取值
char str[] = "age:18";
int age;
sscanf(str, "age:%d", &age);
用途:字符串拼接、解析、协议解析、格式转换。
2. 临时文件 tmpfile ()
自动创建系统临时文件,程序结束自动删除:
c
运行
FILE *fp = tmpfile();
3. ftell /fseek/rewind 二进制文件精确定位
c
运行
fseek(fp, 0, SEEK_END); // 跳到文件末尾
long len = ftell(fp); // 获取文件大小
rewind(fp); // 回到文件开头
用途:读取整个文件大小、分块读写。
4. 格式化输出高级控制
%5d、%-5d、%08x、%.2f 精度控制,日志打印、协议格式化必备。
二、stdlib.h 高阶用法
1. 动态内存高阶
malloc / calloc / realloc / free
- calloc:自动清零
- realloc:动态扩容数组、动态二维数组核心
2. atoi /atof/itoa 类型互转
c
运行
atoi("123"); // 字符串转整数
atof("3.14"); // 字符串转浮点
3. rand 随机数进阶
c
运行
srand((unsigned)time(NULL)); // 设置随机种子
rand() % 100; // 0~99 随机数
4. exit /abort 程序退出
exit(0)正常退出,自动释放资源abort()异常终止,用于程序崩溃兜底
5. qsort 万能快速排序
C 语言通用排序神器,任意类型数组都能排:
c
运行
int cmp(const void *a,const void *b)
{
return *(int*)a - *(int*)b;
}
qsort(arr, n, sizeof(int), cmp);
可排:int、字符串、结构体数组。
三、string.h 高阶用法
1. strlen /strcpy/strcmp /strcat 底层原理
面试常问:自己手写实现四大函数。
2. memcpy 内存拷贝(二进制万能复制)
c
运行
memcpy(dst, src, n);
- 无视类型、直接按字节复制
- 适合:结构体、数组、二进制数据、缓冲区复制
3. memmove 安全内存拷贝
解决内存重叠问题,比 memcpy 更安全。
4. memset 批量初始化
c
运行
memset(arr, 0, sizeof(arr));
快速清零数组、结构体、缓冲区,开发必用。
5. strstr 字符串子串查找
c
运行
strstr("hello world", "world");
用途:关键词检索、协议匹配、敏感词过滤。
6. strtok 字符串分割
按空格、逗号、分号切割字符串,做配置解析、命令解析神器。
总结记忆
- stdio.h:格式化读写、文件定位、字符串解析
sprintf/sscanf/fseek - stdlib.h:动态内存、随机数、类型转换、qsort 万能排序、程序退出
- string.h:字符串处理、内存复制 memcpy、清零 memset、字符串分割查找
更多推荐
所有评论(0)