第19章:C语言常用开发库
C语言的标准库提供了丰富的函数来帮助开发者完成各种常见任务。掌握这些标准库的使用可以大大提高编程效率。
⚠️本章只给出日常开发中常用的函数!
19.1 标准输入输出库(stdio.h)
stdio.h 是最常用的库,提供输入输出功能。
19.1.1 基本输入输出函数
c
#include <stdio.h>
int main() {
int age;
char name[20];
// 输出函数
printf("请输入你的姓名: ");
scanf("%s", name);
printf("请输入你的年龄: ");
scanf("%d", &age);
printf("你好 %s, 你今年 %d 岁\n", name, age);
return 0;
}
19.1.2 文件操作
c
#include <stdio.h>
int main() {
FILE *file;
// 写入文件
file = fopen("test.txt", "w");
if (file != NULL) {
fprintf(file, "这是一行文本\n");
fclose(file);
}
// 读取文件
file = fopen("test.txt", "r");
if (file != NULL) {
char buffer[100];
fgets(buffer, sizeof(buffer), file);
printf("文件内容: %s", buffer);
fclose(file);
}
return 0;
}
19.2 字符串处理库(string.h)
string.h 提供字符串操作函数。
c
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
char result[40];
// 字符串长度
printf("str1长度: %zu\n", strlen(str1));
// 字符串复制
strcpy(result, str1);
printf("复制后: %s\n", result);
// 字符串连接
strcat(result, " ");
strcat(result, str2);
printf("连接后: %s\n", result);
// 字符串比较
if (strcmp(str1, str2) == 0) {
printf("字符串相等\n");
} else {
printf("字符串不相等\n");
}
return 0;
}
19.3 字符处理库(ctype.h)
ctype.h 提供字符分类和转换函数。
c
#include <stdio.h>
#include <ctype.h>
int main() {
char ch = 'A';
// 字符类型判断
printf("%c 是字母: %d\n", ch, isalpha(ch));
printf("%c 是大写: %d\n", ch, isupper(ch));
printf("%c 是数字: %d\n", ch, isdigit(ch));
// 字符转换
char lower = tolower(ch);
char upper = toupper('b');
printf("大写转小写: %c\n", lower);
printf("小写转大写: %c\n", upper);
return 0;
}
19.4 数学库(math.h)
math.h 提供数学计算函数。
c
#include <stdio.h>
#include <math.h>
int main() {
double x = 4.0;
double y = 2.5;
// 基本数学运算
printf("平方根: %.2f\n", sqrt(x));
printf("幂运算: %.2f\n", pow(x, y));
printf("绝对值: %.2f\n", fabs(-3.14));
printf("向上取整: %.2f\n", ceil(y));
printf("向下取整: %.2f\n", floor(y));
return 0;
}
19.5 标准库(stdlib.h)
stdlib.h 提供通用工具函数。
19.5.1 内存分配
c
#include <stdio.h>
#include <stdlib.h>
int main() {
// 动态内存分配
int *arr = (int*)malloc(5 * sizeof(int));
if (arr != NULL) {
for (int i = 0; i < 5; i++) {
arr[i] = i * 10;
}
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
}
return 0;
}
19.5.2 类型转换
c
#include <stdio.h>
#include <stdlib.h>
int main() {
// 字符串转数字
char str[] = "12345";
int num = atoi(str);
printf("字符串转整数: %d\n", num);
char float_str[] = "3.14";
double pi = atof(float_str);
printf("字符串转浮点数: %.2f\n", pi);
return 0;
}
19.5.3 随机数
c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// 设置随机数种子
srand(time(NULL));
// 生成随机数
for (int i = 0; i < 5; i++) {
printf("随机数: %d\n", rand() % 100); // 0-99的随机数
}
return 0;
}
19.6 时间库(time.h)
time.h 提供时间处理函数。
c
#include <stdio.h>
#include <time.h>
int main() {
// 获取当前时间
time_t current_time;
time(¤t_time);
printf("当前时间戳: %ld\n", current_time);
// 转换为可读格式
char* time_str = ctime(¤t_time);
printf("当前时间: %s", time_str);
return 0;
}