C 标准库 - 参考手册学习笔记

1. 概述

C 标准库是 C 语言提供的一组函数库,它们提供了大量功能,包括数学、字符串处理、文件操作等。这些函数被广泛使用,是 C 语言开发中不可或缺的一部分。

2. 数学函数

2.1 abs()

abs() 函数用于获取整数的绝对值。

示例代码:

cCopy Code
#include <stdio.h> #include <stdlib.h> int main(){ int num = -10; int abs_value = abs(num); printf("The absolute value of %d is: %d\n", num, abs_value); return 0; }

输出结果:

Copy Code
The absolute value of -10 is: 10

2.2 pow()

pow() 函数用于计算一个数的幂。

示例代码:

cCopy Code
#include <stdio.h> #include <math.h> int main(){ double base = 3; double exponent = 4; double result = pow(base, exponent); printf("%lf^%lf = %lf\n", base, exponent, result); return 0; }

输出结果:

Copy Code
3.000000^4.000000 = 81.000000

3. 字符串函数

3.1 strlen()

strlen() 函数用于获取字符串的长度。

示例代码:

cCopy Code
#include <stdio.h> #include <string.h> int main(){ char str[] = "Hello, world!"; int len = strlen(str); printf("The length of the string is: %d\n", len); return 0; }

输出结果:

Copy Code
The length of the string is: 13

3.2 strcpy()

strcpy() 函数用于将一个字符串复制到另一个字符串中。

示例代码:

cCopy Code
#include <stdio.h> #include <string.h> int main(){ char src[] = "Hello, world!"; char dest[20]; strcpy(dest, src); printf("The copied string is: %s\n", dest); return 0; }

输出结果:

Copy Code
The copied string is: Hello, world!

4. 文件操作函数

4.1 fopen()

fopen() 函数用于打开一个文件,并返回一个文件指针。

示例代码:

cCopy Code
#include <stdio.h> int main(){ FILE *fp = fopen("test.txt", "r"); if(fp == NULL){ printf("Failed to open file.\n"); return -1; } printf("File opened successfully.\n"); fclose(fp); return 0; }

输出结果:

Copy Code
File opened successfully.

4.2 fgets()

fgets() 函数用于从文件中读取一行数据。

示例代码:

cCopy Code
#include <stdio.h> int main(){ FILE *fp = fopen("test.txt", "r"); if(fp == NULL){ printf("Failed to open file.\n"); return -1; } char buffer[256]; while(fgets(buffer, 256, fp) != NULL){ printf("%s", buffer); } fclose(fp); return 0; }

输出结果:

Copy Code
Hello, world! Welcome to the C standard library reference manual.

以上是关于 C 标准库中的部分常用函数的介绍和使用示例。