一. 标准库 (Standard Library)
核心标准库头文件
#include <stdio.h> // 输入输出
#include <stdlib.h> // 内存管理、系统函数
#include <string.h> // 字符串处理
#include <ctype.h> // 字符处理
#include <math.h> // 数学函数
#include <time.h> // 时间日期
#include <assert.h> // 断言调试
1. 输入输出库 (stdio.h)
#include <stdio.h>
// 文件操作
void file_operations() {
FILE *file = fopen("test.txt", "w");
if (file) {
fprintf(file, "Hello World!\n");
fclose(file);
}
// 读取文件
file = fopen("test.txt", "r");
if (file) {
char buffer[100];
while (fgets(buffer, sizeof(buffer), file)) {
printf("Read: %s", buffer);
}
fclose(file);
}
}
// 格式化输入输出
void formatted_io() {
int age = 25;
double salary = 50000.50;
char name[] = "John";
printf("Name: %s, Age: %d, Salary: %.2f\n", name, age, salary);
// 字符串格式化
char buffer[100];
sprintf(buffer, "Formatted: %s-%d", name, age);
printf("%s\n", buffer);
// 从字符串读取
char input[] = "100 200.5";
int a;
double b;
sscanf(input, "%d %lf", &a, &b);
printf("Parsed: %d, %.1f\n", a, b);
}
2. 字符串处理库 (string.h)
#include <string.h>
#include <stdio.h>
void string_operations() {
char str1[50] = "Hello";
char str2[50] = "World";
char str3[50];
// 字符串长度
printf("Length: %zu\n", strlen(str1));
// 字符串复制
strcpy(str3, str1);
printf("After copy: %s\n", str3);
// 字符串连接
strcat(str3, " ");
strcat(str3, str2);
printf("After concat: %s\n", str3);
// 字符串比较
int result = strcmp(str1, str2);
printf("Compare result: %d\n", result);
// 字符串查找
char *pos = strstr(str3, "World");
if (pos) {
printf("Found 'World' at position: %ld\n", pos - str3);
}
// 内存操作
char buffer[20];
memset(buffer, 'A', 10);
buffer[10] = '\0';
printf("After memset: %s\n", buffer);
// 内存复制
char src[] = "Source";
char dest[20];
memcpy(dest, src, strlen(src) + 1);
printf("After memcpy: %s\n", dest);
}
3. 内存管理库 (stdlib.h)
#include <stdlib.h>
#include <stdio.h>
void memory_operations() {
// 动态内存分配
int *numbers = (int*)malloc(10 * sizeof(int));
if (numbers == NULL) {
perror("malloc failed");
return;
}
// 初始化内存
for (int i = 0; i < 10; i++) {
numbers[i] = i * i;
}
// 重新分配内存
numbers = (int*)realloc(numbers, 20 * sizeof(int));
if (numbers) {
for (int i = 10; i < 20; i++) {
numbers[i] = i * i;
}
}
// 打印结果
for (int i = 0; i < 20; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// 释放内存
free(numbers);
// 其他实用函数
int a = 5, b = 10;
printf("abs(-10) = %d\n", abs(-10));
printf("max(%d, %d) = %d\n", a, b, (a > b) ? a : b);
// 随机数
srand(time(NULL)); // 设置随机种子
printf("Random number: %d\n", rand() % 100);
}
4. 数学库 (math.h)
#include <math.h>
#include <stdio.h>
void math_operations() {
double x = 2.0, y = 3.0;
printf("pow(%.1f, %.1f) = %.2f\n", x, y, pow(x, y));
printf("sqrt(%.1f) = %.2f\n", x, sqrt(x));
printf("sin(%.1f) = %.2f\n", x, sin(x));
printf("cos(%.1f) = %.2f\n", x, cos(x));
printf("log(%.1f) = %.2f\n", x, log(x));
printf("exp(%.1f) = %.2f\n", x, exp(x));
// 三角函数
double angle = 45.0 * M_PI / 180.0; // 转换为弧度
printf("sin(45°) = %.2f\n", sin(angle));
printf("cos(45°) = %.2f\n", cos(angle));
// 取整函数
double num = 3.7;
printf("ceil(%.1f) = %.1f\n", num, ceil(num));
printf("floor(%.1f) = %.1f\n", num, floor(num));
printf("round(%.1f) = %.1f\n", num, round(num));
}
5. 时间和日期库 (time.h)
#include <time.h>
#include <stdio.h>
void time_operations() {
// 获取当前时间
time_t current_time = time(NULL);
printf("Current timestamp: %ld\n", current_time);
// 转换为可读格式
char *time_str = ctime(¤t_time);
printf("Current time: %s", time_str);
// 使用结构体获取详细时间
struct tm *time_info = localtime(¤t_time);
printf("Year: %d\n", time_info->tm_year + 1900);
printf("Month: %d\n", time_info->tm_mon + 1);
printf("Day: %d\n", time_info->tm_mday);
printf("Hour: %d\n", time_info->tm_hour);
printf("Minute: %d\n", time_info->tm_min);
printf("Second: %d\n", time_info->tm_sec);
// 格式化时间输出
char buffer[80];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", time_info);
printf("Formatted: %s\n", buffer);
// 计算程序运行时间
clock_t start = clock();
// 模拟一些工作
for (long i = 0; i < 100000000; i++) {
// 空循环
}
clock_t end = clock();
double cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("CPU time used: %.2f seconds\n", cpu_time_used);
}
6. 字符处理库 (ctype.h)
#include <ctype.h>
#include <stdio.h>
void character_operations() {
char ch = 'A';
char digit = '5';
char space = ' ';
char punct = '!';
printf("isalpha('%c'): %d\n", ch, isalpha(ch));
printf("isdigit('%c'): %d\n", digit, isdigit(digit));
printf("isspace('%c'): %d\n", space, isspace(space));
printf("isalnum('%c'): %d\n", ch, isalnum(ch));
printf("ispunct('%c'): %d\n", punct, ispunct(punct));
printf("isupper('%c'): %d\n", ch, isupper(ch));
printf("islower('%c'): %d\n", ch, islower(ch));
// 字符转换
char lower = tolower(ch);
char upper = toupper('b');
printf("tolower('%c') = '%c'\n", ch, lower);
printf("toupper('b') = '%c'\n", upper);
// 实用示例:字符串处理
char text[] = "Hello World 123!";
printf("Original: %s\n", text);
printf("Processed: ");
for (int i = 0; text[i]; i++) {
if (isalpha(text[i])) {
putchar(toupper(text[i]));
} else if (isdigit(text[i])) {
putchar(text[i]);
} else {
putchar(' ');
}
}
printf("\n");
}
7. 实用工具库 (stdlib.h 扩展)
#include <stdlib.h>
#include <stdio.h>
void utility_operations() {
// 环境变量
char *path = getenv("PATH");
if (path) {
printf("PATH: %s\n", path);
}
// 系统命令
printf("System output:\n");
system("ls -la"); // Linux/Mac
// system("dir"); // Windows
// 字符串转换
char num_str[] = "12345";
int number = atoi(num_str);
printf("atoi('%s') = %d\n", num_str, number);
char float_str[] = "3.14159";
double pi = atof(float_str);
printf("atof('%s') = %.5f\n", float_str, pi);
// 更安全的转换函数
char *endptr;
long big_num = strtol("1234567890", &endptr, 10);
printf("strtol result: %ld\n", big_num);
// 退出程序
// exit(EXIT_SUCCESS); // 正常退出
// exit(EXIT_FAILURE); // 错误退出
}
8. 错误处理库 (errno.h)
#include <errno.h>
#include <stdio.h>
#include <string.h>
void error_handling() {
FILE *file = fopen("nonexistent_file.txt", "r");
if (file == NULL) {
printf("Error opening file: %s\n", strerror(errno));
perror("fopen failed");
}
// 清除错误状态
errno = 0;
// 数学错误示例
double result = sqrt(-1.0);
if (errno != 0) {
printf("Math error: %s\n", strerror(errno));
}
}
9. 断言调试库 (assert.h)
#include <assert.h>
#include <stdio.h>
int divide(int a, int b) {
assert(b != 0); // 断言:除数不能为0
return a / b;
}
void assertion_demo() {
printf("Testing assertion...\n");
// 正常情况
int result = divide(10, 2);
printf("10 / 2 = %d\n", result);
// 错误情况(在调试模式下会终止程序)
// result = divide(10, 0); // 这会触发断言失败
// 自定义错误检查
int value = -5;
assert(value >= 0 && "Value must be non-negative");
}