C语言系统函数-(新增)

一、输入输出函数(I/O)

头文件<stdio.h>

函数 功能 示例
printf() 格式化输出到标准输出 printf("Hello, %s!\n", name);
scanf() 从标准输入读取格式化数据 scanf("%d", &num);
gets() / fgets() 读取字符串(gets 已废弃,推荐 fgets fgets(buffer, 100, stdin);
puts() 输出字符串并换行 puts("Hello");
fopen() / fclose() 打开/关闭文件 FILE *fp = fopen("file.txt", "r");
fprintf() / fscanf() 文件格式化输入输出 fprintf(fp, "%d", value);
fread() / fwrite() 二进制读写 fread(buffer, 1, size, fp);

二、字符串处理函数

头文件<string.h>

函数 功能 示例
strcpy() 字符串复制 strcpy(dest, src);
strcat() 字符串拼接 strcat(str1, str2);
strlen() 获取字符串长度 int len = strlen(s);
strcmp() 字符串比较 if (strcmp(s1, s2) == 0)
strstr() 查找子串 char *p = strstr(haystack, needle);
strchr() / strrchr() 查找字符首次/最后一次出现位置 char *p = strchr(s, 'a');
memset() / memcpy() / memmove() 内存操作 memset(buffer, 0, 100);

⚠️ 注意:strcpystrcat 等不检查边界,易导致缓冲区溢出,推荐使用更安全的 strncpystrncat(需手动补 \0)。


三、内存管理函数

头文件<stdlib.h>

函数 功能 示例
malloc() 动态分配内存 int *p = (int*)malloc(10 * sizeof(int));
calloc() 分配并初始化为 0 int *p = (int*)calloc(10, sizeof(int));
realloc() 重分配内存 p = realloc(p, 20 * sizeof(int));
free() 释放内存 free(p);

注意:使用后需 free(),避免内存泄漏;释放后应将指针置为 NULL


四、数学函数

头文件<math.h>

函数 功能 示例
sqrt() 平方根 double r = sqrt(16.0); // 4.0
pow() 幂运算 double x = pow(2, 3); // 8
sin() / cos() / tan() 三角函数 double s = sin(M_PI / 2);
abs() 整数绝对值(<stdlib.h> int a = abs(-5);
fabs() 浮点绝对值 double f = fabs(-3.14);
ceil() / floor() 向上/向下取整 double c = ceil(3.2); // 4.0

编译时通常需链接数学库:gcc file.c -lm


五、字符处理函数

头文件<ctype.h>

函数 功能 示例
isalpha() 是否为字母 if (isalpha(c))
isdigit() 是否为数字 if (isdigit(c))
isalnum() 字母或数字 if (isalnum(c))
islower() / isupper() 小写/大写判断 if (isupper(c))
tolower() / toupper() 转换大小写 c = tolower('A'); // 'a'

六、时间与日期函数

头文件<time.h>

函数 功能 示例
time() 获取当前时间(秒) time_t t = time(NULL);
ctime() 转为可读字符串 printf("%s", ctime(&t));
localtime() / gmtime() 转为本地/UTC 时间结构 struct tm *tm = localtime(&t);
strftime() 格式化时间输出 strftime(buf, 80, "%Y-%m-%d", tm);

七、程序控制与实用函数

头文件<stdlib.h>

函数 功能 示例
exit() 终止程序 exit(0);
atoi() / atof() / atol() 字符串转数字 int n = atoi("123");
rand() / srand() 随机数生成 srand(time(NULL)); int r = rand();
system() 执行系统命令 system("ls");(Unix)或 system("dir");(Windows)

随机数注意:srand() 只需调用一次(通常在 main 开头)。


八、错误处理

头文件<errno.h>

  • 全局变量 errno:记录最近一次系统调用错误码。
  • perror():打印错误信息。

总结:常用头文件速查

功能类别 头文件
输入输出 <stdio.h>
字符串 <string.h>
内存/通用 <stdlib.h>
数学 <math.h>
字符判断 <ctype.h>
时间日期 <time.h>
错误码 <errno.h>
相关推荐
WXG10111 小时前
【matlab】matlab点云处理
开发语言·matlab
♛识尔如昼♛1 小时前
C 基础(3-2) - 数据和C
c语言·开发语言
多多想1 小时前
C++扫盲——为什么C/C++分文件要写h和cpp?
c语言·c++
liulilittle1 小时前
C++判断wchar_t空白字符
开发语言·c++
花阴偷移2 小时前
kotlin语法(上)
android·java·开发语言·kotlin
XuanRanDev2 小时前
【编程语言】Kotlin快速入门 - 泛型
开发语言·kotlin
普通网友2 小时前
Android kotlin Jetpack mvvm 项目
android·开发语言·kotlin
Crogin2 小时前
快速简单入门Kotlin——基础语法(第一天)
android·开发语言·kotlin
qq_336313932 小时前
java基础-set系列集合
java·开发语言·python