C语言函数大全--j开头的函数

总览

函数声明 函数功能
double j0 (double x); 计算 x 的 第一类 0 阶贝塞尔函数(double)
float j0f (float x); 计算 x 的 第一类 0 阶贝塞尔函数(float)【笔者本地windows环境,无此函数】
double j1 (double x); 计算 x 的 第一类 1 阶贝塞尔函数(double)
float j1f (float x); 计算 x 的 第一类 1 阶贝塞尔函数(float)【笔者本地windows环境,无此函数】
double jn (int n, double x); 计算 x第一类 n 阶贝塞尔函数(double)
float jnf (int n, float x); 计算 x第一类 n 阶贝塞尔函数(float)【笔者本地windows环境,无此函数】
double jrand48(); 生成伪随机数序列
int join(pthread_t thread, void **retval); 等待线程退出并回收资源
typedef _JBTYPE jmp_buf[_JBLEN]; 它是一个数组类型,保存跳转目标地址的缓冲区。通常与 setjmp 和 longjmp 函数一起使用,用于实现非局部跳转
u32 jhash(const void *key, u32 length, u32 initval); 它是 Linux 内核头文件 linux/jhash.h 中的一个函数,用于实现一种高效的哈希算法。
unsigned long volatile jiffies; 它是 Linux 内核中的一个全局变量,表示内核启动后经过的节拍数。其中 volatile 关键字用于告知编译器在访问这个变量时不要使用缓存,以确保能够正确读取最新值。
u64 jiffies_64; 它是 Linux 内核中的一个全局变量,类似于 jiffies,但是支持更大的取值范围。其中 u6464 位无符号整型。
clock_t jiffies_delta_to_clock_t(unsigned long delta); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于计算两个 jiffies 值之间的时间差,并将结果转换为 clock_t 类型的值。
unsigned long jiffies_delta_to_msecs(unsigned long delta); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于计算两个 jiffies 值之间的时间差,并将结果转换为毫秒数
clock_t jiffies_to_clock_t(unsigned long jiffies); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于将 jiffies 值(内核节拍数)转换为 clock_t 类型的值。
unsigned long jiffies_to_msecs(const unsigned long j); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于将 jiffies 值(内核节拍数)转换为毫秒数。
clock_t jiffies64_to_clock_t(u64 jiffies); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于将 64 位 jiffies 值(内核节拍数)转换为 clock_t 类型的值。
u64 jiffies64_to_msecs(const u64 jiffies); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于将 64 位 jiffies 值(内核节拍数)转换为毫秒数。
void jiffies_update_wallclock(void); 它是 Linux 内核头文件 linux/time.h 中的一个函数,用于更新系统时钟的时间戳。

1. j0,j0f

1.1 函数说明

函数声明 函数功能
double j0 (double x); 计算 x 的 第一类 0 阶贝塞尔函数(double)
float j0f (float x); 计算 x 的 第一类 0 阶贝塞尔函数(float)【笔者本地windows环境,无此函数】

注意: 如果操作成功,则返回 x第一类 0 阶贝塞尔函数;如果 xNaN 值,则返回 NaN 值;如果 x 太大或发生溢出范围错误,则返回 0 并将 errno 设置为 ERANGE

1.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <math.h>
int main()
{
double x = 10.0, result;
result = j0(x);

printf("%lf 的 第一类 0 阶贝塞尔函数 : %lf", x, result);

return 0;
}

1.3 运行结果

2. j1,j1f

2.1 函数说明

函数声明 函数功能
double j1 (double x); 计算 x 的 第一类 1 阶贝塞尔函数(double)
float j1f (float x); 计算 x 的 第一类 1 阶贝塞尔函数(float)【笔者本地windows环境,无此函数】

注意: 如果操作成功,则返回 x第一类 1 阶贝塞尔函数;如果 xNaN 值,则返回 NaN 值;如果 x 太大或发生溢出范围错误,则返回 0 并将 errno 设置为 ERANGE

2.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <math.h>
int main()
{
double x = 10.0, result;
result = j1(x);

printf("%lf 的 第一类 1 阶贝塞尔函数 : %lf", x, result);

return 0;
}

2.3 运行结果

3. jn,jnf

3.1 函数说明

函数声明 函数功能
double jn (int n, double x); 计算 x第一类 n 阶贝塞尔函数(double)
float jnf (int n, float x); 计算 x第一类 n 阶贝塞尔函数(float)【笔者本地windows环境,无此函数】

注意: 如果操作成功,则返回 x第一类 n 阶贝塞尔函数;如果 xNaN 值,则返回 NaN 值;如果 x 太大或发生溢出范围错误,则返回 0 并将 errno 设置为 ERANGE

3.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <math.h>

void jnPrint(int n, double x);

int main()
{
double x = 10.0;
jnPrint(2, x);
jnPrint(3, x);
jnPrint(4, x);
return 0;
}

void jnPrint(int n, double x)
{
double result = jn(n, x);
printf("%lf 的 第一类 %d 阶贝塞尔函数 : %lf\n", x, n, result);
}

3.3 运行结果

4. jrand48

4.1 函数说明

函数声明 函数功能
double jrand48(); 生成伪随机数序列

jrand48 函数是一个生成伪随机数序列的函数,并且它是可重入的,即可以在多个线程中同时调用而不会出现冲突。

4.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main() {
// 初始化种子
srand48(time(NULL));

// 生成10个随机数
for (int i = 0; i < 5; ++i) {
double r = jrand48();
printf("%f\n", r);
}

return 0;
}

上述程序首先通过 srand48 函数初始化随机数生成器的种子,这里使用了当前系统时间作为种子。然后循环调用 jrand48 函数 5 次,每次输出一个伪随机数。注意,由于 jrand48 函数返回的是一个双精度浮点数(范围在 [0, 1) 内),因此输出时需要使用 %f 格式化符号。

5. join

5.1 函数说明

函数声明 函数功能
int join(pthread_t thread, void **retval); 等待线程退出并回收资源

C 语言中,join 函数不是标准库函数,也不是 POSIX 标准的函数。然而,一些操作系统(如 UNIX/Linux)提供了 join 函数用于等待线程退出并回收资源。在 POSIX 线程中,相应的函数是 pthread_join

5.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *thread_func(void *arg) {
printf("Thread is running...\n");
pthread_exit(NULL);
}

int main() {
pthread_t thread;
if (pthread_create(&thread, NULL, thread_func, NULL)) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
printf("Main thread is waiting for the child thread to exit...\n");
join(thread, NULL);
printf("Child thread has exited.\n");
return EXIT_SUCCESS;
}

上述程序创建了一个新线程,并且主线程等待新线程退出后才继续执行。在新线程中,打印一条消息并调用 pthread_exit 函数退出线程。在主线程中,调用 join 函数等待新线程退出,并通过 NULL 参数指示不需要返回值。最终输出一条消息表示新线程已经退出。

6. jmp_buf

6.1 类型说明

类型定义 描述
typedef _JBTYPE jmp_buf[_JBLEN]; 它是一个数组类型,保存跳转目标地址的缓冲区。通常与 setjmp 和 longjmp 函数一起使用,用于实现非局部跳转

6.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

jmp_buf env;

void func() {
printf("Entering func...\n");
longjmp(env, 1);
printf("This line will not be executed.\n");
}

int main() {
int ret = setjmp(env);
if (ret == 0) {
printf("Jumping to func...\n");
func();
} else {
printf("Returning from longjmp with value %d\n", ret);
}
return EXIT_SUCCESS;
}

上述程序定义了一个名为 envjmp_buf 类型变量,用于保存当前执行状态。在主函数中,通过调用 setjmp 函数将当前状态保存到
env 中,并返回 0。然后调用 func 函数,该函数打印一条消息并调用 longjmp 函数恢复之前保存的状态,这里传入参数值为 1。由于 longjmp 函数会导致程序跳转到 setjmp 函数继续执行,因此后面的 printf 语句会输出 "Returning from longjmp with value 1"

需要注意的是,在使用 jmp_bufsetjmplongjmp 函数时需要遵循特定的使用规范,否则可能会导致未定义行为或错误。

6.3 运行结果

7. jhash

7.1 函数说明

函数声明 函数功能
u32 jhash(const void *key, u32 length, u32 initval); 它是 Linux 内核头文件 linux/jhash.h 中的一个函数,用于实现一种高效的哈希算法。

参数:

  • key : 要进行哈希的数据
  • length : 数据的长度(以字节为单位)
  • initval : 哈希值的初始值。

7.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/jhash.h>

int my_init(void)
{
char data[] = "Hello, world!";
u32 hash;

printk(KERN_INFO "Initializing module...\n");

/* calculate hash value */
hash = jhash(data, strlen(data), 0);
printk(KERN_INFO "Hash value: %u\n", hash);

return 0;
}

void my_exit(void)
{
printk(KERN_INFO "Exiting module...\n");
}

MODULE_LICENSE("GPL");
module_init(my_init);
module_exit(my_exit);

上述示例程序中,在 my_init() 函数中定义了一个字符串 data,并使用 jhash() 函数计算出其哈希值,并打印出来。

注意: 虽然 jhash() 函数可以用于快速查找和管理数据结构等,但在使用时必须充分理解其作用原理和使用方法,避免因为错误使用导致哈希冲突或其他问题。同时,应当根据具体情况选择合适的哈希算法,并考虑其效率和安全性等方面的因素。

8. jiffies,jiffies_64

8.1 变量说明

变量声明 变量描述
unsigned long volatile jiffies; 它是 Linux 内核中的一个全局变量,表示内核启动后经过的节拍数。其中 volatile 关键字用于告知编译器在访问这个变量时不要使用缓存,以确保能够正确读取最新值。
u64 jiffies_64; 它是 Linux 内核中的一个全局变量,类似于 jiffies,但是支持更大的取值范围。其中 u6464 位无符号整型。

8.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/jiffies.h>

int my_init(void)
{
u64 start = jiffies_64;
u64 end;

printk(KERN_INFO "Initializing module...\n");

/* do some work */
mdelay(1000);

/* calculate elapsed time in jiffies_64 */
end = jiffies_64 - start;
printk(KERN_INFO "Elapsed time: %llu jiffies_64\n", end);

return 0;
}

void my_exit(void)
{
printk(KERN_INFO "Exiting module...\n");
}

MODULE_LICENSE("GPL");
module_init(my_init);
module_exit(my_exit);

上述示例程序中,在 my_init() 函数中获取了当前的 jiffies_64 值,并使用 mdelay() 函数让程序阻塞一段时间。在之后,通过计算当前的 jiffies_64 值与之前的 jiffies_64 值之差,计算出经过的时间并打印出来。

注意: jiffiesjiffies_64 值每隔一段时间就会发生一次溢出,在处理 jiffiesjiffies_64 值时必须注意这个问题,避免计算结果错误。另外,jiffiesjiffies_64 变量只能在内核空间中使用,不能在用户空间中使用。

9. jiffies_delta_to_clock_t

9.1 函数说明

函数声明 函数功能
clock_t jiffies_delta_to_clock_t(unsigned long delta); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于计算两个 jiffies 值之间的时间差,并将结果转换为 clock_t 类型的值。

参数:

  • delta : 要计算的 jiffies 时间差值。

9.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/jiffies.h>

int my_init(void)
{
unsigned long start = jiffies;
unsigned long end;
clock_t ticks;

printk(KERN_INFO "Initializing module...\n");

/* do some work */
mdelay(1000);

/* calculate elapsed time in jiffies and convert to ticks */
end = jiffies;
ticks = jiffies_delta_to_clock_t(end - start);
printk(KERN_INFO "Elapsed time: %ld ticks\n", (long)ticks);

return 0;
}

void my_exit(void)
{
printk(KERN_INFO "Exiting module...\n");
}

MODULE_LICENSE("GPL");
module_init(my_init);
module_exit(my_exit);

上述示例程序中,在 my_init() 函数中获取了当前的 jiffies 值,并使用 mdelay() 函数让程序阻塞一段时间。在之后,通过计算当前的 jiffies 值与之前的 jiffies 值之差,并调用 jiffies_delta_to_clock_t() 函数,计算出经过的时间并打印出来。

注意: 在使用 jiffies_delta_to_clock_t() 函数时,返回值类型是 clock_t,不同于 jiffies_delta_to_msecs() 函数的返回值类型是 unsigned long。另外,clock_t 的定义可能因系统而异,应当根据具体情况进行处理。

10. jiffies_delta_to_msecs

10.1 函数说明

函数声明 函数功能
unsigned long jiffies_delta_to_msecs(unsigned long delta); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于计算两个 jiffies 值之间的时间差,并将结果转换为毫秒数

参数:

  • delta : 要计算的 jiffies 时间差值。

10.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/jiffies.h>

int my_init(void)
{
unsigned long start = jiffies;
unsigned long end;
unsigned long msecs;

printk(KERN_INFO "Initializing module...\n");

/* do some work */
mdelay(1000);

/* calculate elapsed time in jiffies and convert to milliseconds */
end = jiffies;
msecs = jiffies_delta_to_msecs(end - start);
printk(KERN_INFO "Elapsed time: %lu ms\n", msecs);

return 0;
}

void my_exit(void)
{
printk(KERN_INFO "Exiting module...\n");
}

MODULE_LICENSE("GPL");
module_init(my_init);
module_exit(my_exit);

上述示例程序中,在 my_init() 函数中获取了当前的 jiffies 值,并使用 mdelay() 函数让程序阻塞一段时间。在之后,通过计算当前的 jiffies 值与之前的 jiffies 值之差,并调用 jiffies_delta_to_msecs() 函数,计算出经过的时间并打印出来。

注意: 在使用 jiffies_delta_to_msecs() 函数时,返回值类型是 unsigned long,不同于 jiffies_delta_to_clock_t() 函数的返回值类型是 clock_t。另外,由于 jiffies 的精度限制,计算结果可能存在一定的误差。

11. jiffies_to_clock_t

11.1 函数说明

函数声明 函数功能
clock_t jiffies_to_clock_t(unsigned long jiffies); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于将 jiffies 值(内核节拍数)转换为 clock_t 类型的值。

参数:

  • jiffies: 要转换的 jiffies 值,它是 Linux 内核中的一个全局变量,表示内核启动后经过的节拍数。

11.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/jiffies.h>

int my_init(void)
{
unsigned long j = jiffies;
clock_t ticks;

printk(KERN_INFO "Initializing module...\n");

/* do some work */
mdelay(1000);

/* calculate elapsed time in ticks */
ticks = jiffies_to_clock_t(jiffies - j);
printk(KERN_INFO "Elapsed time: %ld ticks\n", (long)ticks);

return 0;
}

void my_exit(void)
{
printk(KERN_INFO "Exiting module...\n");
}

MODULE_LICENSE("GPL");
module_init(my_init);
module_exit(my_exit);

上述示例程序中,在 my_init() 函数中获取了当前的 jiffies 值,并使用 mdelay() 函数让程序阻塞一段时间。在之后,通过计算当前的 jiffies 值与之前的 jiffies 值之差并调用 jiffies_to_clock_t() 函数,计算出经过的时间,并打印出来。

注意: 在使用 jiffies_to_clock_t() 函数时,返回值类型是 clock_t,不同于 jiffies_to_msecs() 函数的返回值类型是 unsigned long。另外,clock_t 的定义可能因系统而异,应当根据具体情况进行处理。

12. jiffies_to_msecs

12.1 函数说明

函数声明 函数功能
unsigned long jiffies_to_msecs(const unsigned long j); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于将 jiffies 值(内核节拍数)转换为毫秒数。

参数:

  • j: 要转换的 jiffies 值,它是 Linux 内核中的一个全局变量,表示内核启动后经过的节拍数。

12.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/jiffies.h>

int my_init(void)
{
unsigned long j = jiffies;
unsigned long ms;

printk(KERN_INFO "Initializing module...\n");

/* do some work */
mdelay(1000);

/* calculate elapsed time in milliseconds */
ms = jiffies_to_msecs(jiffies - j);
printk(KERN_INFO "Elapsed time: %lu ms\n", ms);

return 0;
}

void my_exit(void)
{
printk(KERN_INFO "Exiting module...\n");
}

MODULE_LICENSE("GPL");
module_init(my_init);
module_exit(my_exit);

上述示例程序中,在 my_init() 函数中获取了当前的 jiffies 值,并使用 mdelay() 函数让程序阻塞一段时间。在之后,通过计算当前的 jiffies 值与之前的 jiffies 值之差并调用 jiffies_to_msecs() 函数,计算出经过的时间,并打印出来。

注意: 在使用 jiffies_to_msecs() 函数时,必须十分小心地处理 jiffies 值的溢出等问题,以免计算结果错误。另外,jiffies_to_msecs() 函数只能用于内核空间中,不能在用户空间中使用。

13. jiffies64_to_clock_t

13.1 函数说明

函数声明 函数功能
clock_t jiffies64_to_clock_t(u64 jiffies); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于将 64 位 jiffies 值(内核节拍数)转换为 clock_t 类型的值。

参数:

  • jiffies : 要转换的 64jiffies 值。

13.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/jiffies.h>

int my_init(void)
{
u64 start = jiffies_64;
u64 end;
clock_t ticks;

printk(KERN_INFO "Initializing module...\n");

/* do some work */
mdelay(1000);

/* calculate elapsed time in jiffies_64 and convert to ticks */
end = jiffies_64;
ticks = jiffies64_to_clock_t(end - start);
printk(KERN_INFO "Elapsed time: %ld ticks\n", (long)ticks);

return 0;
}

void my_exit(void)
{
printk(KERN_INFO "Exiting module...\n");
}

MODULE_LICENSE("GPL");
module_init(my_init);
module_exit(my_exit);

上述示例程序中,在 my_init() 函数中获取了当前的 64jiffies_64 值,并使用 mdelay() 函数让程序阻塞一段时间。在之后,通过计算当前的 64jiffies_64 值与之前的 jiffies_64 值之差,并调用 jiffies64_to_clock_t() 函数,计算出经过的时间并打印出来。

14. jiffies64_to_msecs

14.1 函数说明

函数声明 函数功能
u64 jiffies64_to_msecs(const u64 jiffies); 它是 Linux 内核头文件 linux/jiffies.h 中的一个函数,用于将 64 位 jiffies 值(内核节拍数)转换为毫秒数。

参数:

  • jiffies : 要转换的 64jiffies 值。

14.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/jiffies.h>

int my_init(void)
{
u64 start = jiffies_64;
u64 end;
u64 msecs;

printk(KERN_INFO "Initializing module...\n");

/* do some work */
mdelay(1000);

/* calculate elapsed time in jiffies_64 and convert to milliseconds */
end = jiffies_64;
msecs = jiffies64_to_msecs(end - start);
printk(KERN_INFO "Elapsed time: %llu ms\n", msecs);

return 0;
}

void my_exit(void)
{
printk(KERN_INFO "Exiting module...\n");
}

MODULE_LICENSE("GPL");
module_init(my_init);
module_exit(my_exit);

上述示例程序中,在 my_init() 函数中获取了当前的 64jiffies_64 值,并使用 mdelay() 函数让程序阻塞一段时间。在之后,通过计算当前的 64jiffies_64 值与之前的 jiffies_64 值之差,并调用 jiffies64_to_msecs() 函数,计算出经过的时间并打印出来。

15. jiffies_update_wallclock

15.1 函数说明

函数声明 函数功能
void jiffies_update_wallclock(void); 它是 Linux 内核头文件 linux/time.h 中的一个函数,用于更新系统时钟的时间戳。

15.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/jiffies.h>

int my_init(void)
{
printk(KERN_INFO "Initializing module...\n");

/* do some work */
mdelay(1000);

/* update wall clock */
jiffies_update_wallclock();

return 0;
}

void my_exit(void)
{
printk(KERN_INFO "Exiting module...\n");
}

MODULE_LICENSE("GPL");
module_init(my_init);
module_exit(my_exit);

上述示例程序中,在 my_init() 函数中使用 mdelay() 函数让程序阻塞一段时间,在之后调用 jiffies_update_wallclock() 函数更新系统时钟的时间戳。

注意: jiffies_update_wallclock() 函数只能在内核空间中使用,不能在用户空间中使用。另外,如果系统使用了 NTP 等网络时间同步服务,可能无法通过 jiffies_update_wallclock() 函数来准确更新系统时钟。

参考

  1. [MATH-标准C库]
  2. 《Linux内核API完全参考手册》

C语言函数大全--i开头的函数

总览

函数声明 函数功能
unsigned imagesize(int left, int top, int right, int bottom); 获取保存位图像所需的字节数
void initgraph( int *graphdriver, int *graphmode, char *pathtodriver ); 初始化图形系统
int inport(int protid); 从硬件端口中输入
void insline(void); 在文本窗口中插入一个空行
int installuserdriver(char *name, int (*detect)(void)); 安装设备驱动程序到BGI设备驱动程序表中
int installuserfont( char *name ); 安装未嵌入BGI系统的字体文件(CHR)
int int86(int intr_num, union REGS *inregs, union REGS *outregs); 通用8086软中断接口
int int86x(int intr_num, union REGS *insegs, union REGS *outregs, struct SREGS *segregs); 通用8086软中断接口
int intdos(union REGS *inregs, union REGS *outregs); 通用DOS接口
int intdosx(union REGS *inregs, union REGS *outregs, struct SREGS *segregs); 通用DOS中断接口
void intr(int intr_num, struct REGPACK *preg); 改变软中断接口
int ioctl(int fd, int cmd, ...) ; 控制 I/O 设备
int isatty(int handle); 检查设备类型
int ilogb (double x); 获取 x 的对数的积分部分(double)
int ilogbf (float x); 获取 x 的对数的积分部分(float)
int ilogbl (long double x); 获取 x 的对数的积分部分(long double)
char * itoa(int value, char *string, int radix); 把一整数转换为字符串

1. imagesize

1.1 函数说明

函数声明 函数功能
unsigned imagesize(int left, int top, int right, int bottom); 获取保存位图像所需的字节数

参数:

  • left :矩形区域左边界的 x 坐标(水平方向起始位置)。
  • top :矩形区域上边界的 y 坐标(垂直方向起始位置)。
  • right :矩形区域右边界的 x 坐标(水平方向结束位置,需满足 right >= left)。
  • bottom :矩形区域下边界的 y 坐标(垂直方向结束位置,需满足 bottom >= top)。

1.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

#define ARROW_SIZE 10

void draw_arrow(int x, int y);

int main()
{
int gdriver = DETECT, gmode, errorcode;
void *arrow;
int x, y, maxx;
unsigned int size;

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

maxx = getmaxx();
x = 0;
y = getmaxy() / 2;

draw_arrow(x, y);

size = imagesize(x, y-ARROW_SIZE, x+(4*ARROW_SIZE), y+ARROW_SIZE);

// 分配内存以保存图像
arrow = malloc(size);

// 抓取图像
getimage(x, y-ARROW_SIZE, x+(4*ARROW_SIZE), y+ARROW_SIZE, arrow);

// 重复,直到按键被按下
while (!kbhit())
{
// 擦除旧图像
putimage(x, y-ARROW_SIZE, arrow, XOR_PUT);

x += ARROW_SIZE;
if (x >= maxx)
x = 0;

// 绘制新图像
putimage(x, y-ARROW_SIZE, arrow, XOR_PUT);
}

free(arrow);
closegraph();
return 0;
}

void draw_arrow(int x, int y)
{
// 在屏幕上画一个箭头
moveto(x, y);
linerel(4*ARROW_SIZE, 0);
linerel(-2*ARROW_SIZE, -1*ARROW_SIZE);
linerel(0, 2*ARROW_SIZE);
linerel(2*ARROW_SIZE, -1*ARROW_SIZE);
}

上述代码利用图形库实现了一个在屏幕上移动箭头图形的动画效果。

1.3 运行结果

2. initgraph

2.1 函数说明

函数声明 函数功能
void initgraph( int *graphdriver, int *graphmode, char *pathtodriver); 初始化图形系统

参数:

  • int *graphdriver : 一个指向整数的指针。用于指定要使用的图形驱动程序。图形驱动程序是一组软件代码,负责与特定的图形硬件进行通信。常见的图形驱动程序有 DETECT(自动检测系统中可用的图形硬件并选择合适的驱动程序)、EGAVGA_driver(用于 EGA 或 VGA 显示器)等。
  • int *graphmode :一个指向整数的指针。用于指定要使用的图形模式。不同的图形驱动程序支持多种图形模式,每种模式具有不同的分辨率、颜色深度等特性。如果 graphdriver 参数设置为 DETECT,则可以将 graphmode 指针指向的变量初始化为 0,让系统自动选择合适的图形模式。
  • char *pathtodriver :一个指向字符的指针。用于指定图形驱动程序文件的路径。图形驱动程序通常以 .BGI 为扩展名的文件形式存在。如果该参数设置为 ""(空字符串),则系统会在当前目录下查找图形驱动程序文件。

2.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
int gdriver = DETECT, gmode, errorcode;
// 初始化图形系统
initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

line(0, 0, getmaxx(), getmaxy());

getch();
closegraph();
return 0;
}

2.3 运行结果

3. inport

3.1 函数说明

函数声明 函数功能
int inport(int protid); 从硬件端口中输入,即从指定的 I/O 端口读取一个 16 位(2 字节)的数据

参数:

  • portid :要读取数据的 I/O 端口号。不同的硬件设备会使用不同的端口号,比如,键盘控制器常用的端口号是 0x60。在使用 inport 函数时,需要根据具体的硬件设备和操作需求来确定正确的端口号。

返回值:
从指定 I/O 端口读取到的 16 位数据。若读取过程中出现错误,返回值的具体情况可能因系统和硬件而异。

3.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <dos.h>

int main()
{
int result;
int port = 0; // 串行端口 0
// 从硬件端口中输入
result = inport(port);
printf("Word read from port %d = 0x%X\n", port, result);
return 0;
}

4. insline

4.1 函数说明

函数声明 函数功能
void insline(void); 在当前光标位置插入一行空行,原光标所在行及其下方的所有行都会向下移动一行 【在 Turbo C 等早期 C 编译器的图形库或控制台操作库中使用】

4.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <conio.h>

int main()
{
clrscr();
cprintf("INSLINE inserts an empty line in the text window\r\n");
cprintf("at the cursor position using the current text\r\n");
cprintf("background color. All lines below the empty one\r\n");
cprintf("move down one line and the bottom line scrolls\r\n");
cprintf("off the bottom of the window.\r\n");
cprintf("\r\nPress any key to continue:");
gotoxy(1, 3);
getch();
// 在文本窗口中插入一个空行
insline();
getch();
return 0;
}

5. installuserdriver

5.1 函数说明

函数声明 函数功能
int installuserdriver(char *name, int (*detect)(void)); 安装设备驱动程序到BGI设备驱动程序表中

注意: 该函数在 WinBGI 中不可用

5.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int huge detectEGA(void);
void checkerrors(void);

int main(void)
{
int gdriver, gmode;
// 安装用户编写的设备驱动程序
gdriver = installuserdriver("EGA", detectEGA);
// 必须强制使用检测程序
gdriver = DETECT;
// 检查是否有任何安装错误
checkerrors();
// 初始化图形程序
initgraph(&gdriver, &gmode, "");
// 检查是否有任何初始化错误
checkerrors();
// 画一条对象线
line(0, 0, getmaxx(), getmaxy());

getch();
closegraph();
return 0;
}

/*
检测EGA或VGA卡
*/
int huge detectEGA(void);
{
int driver, mode, sugmode = 0;
detectgraph(&driver, &mode);
if ((driver == EGA) || (driver == VGA))
return sugmode; // 返回建议的视频模式编号
else
return grError; // 返回错误代码
}

/*
检查并报告任何图形错误
*/
void checkerrors(void)
{
// 获取上次图形操作的读取结果
int errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}
}

6. installuserfont

6.1 函数说明

函数声明 函数功能
int installuserfont( char *name ); 安装未嵌入BGI系统的字体文件(CHR)

注意: 该函数在 WinBGI 中不可用

6.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

void checkerrors(void);

int main()
{
int gdriver = DETECT, gmode;
int userfont;
int midx, midy;

initgraph(&gdriver, &gmode, "");

midx = getmaxx() / 2;
midy = getmaxy() / 2;

checkerrors();

// 安装用户定义的字体文件
userfont = installuserfont("USER.CHR");

checkerrors();

// 选择用户字体
settextstyle(userfont, HORIZ_DIR, 4);

outtextxy(midx, midy, "Testing!");

getch();
closegraph();
return 0;
}

/*
检查并报告任何图形错误
*/
void checkerrors(void)
{
// 获取上次图形操作的读取结果
int errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}
}

7. int86

7.1 函数说明

函数声明 函数功能
int int86(int intr_num, union REGS *inregs, union REGS *outregs); 通用8086软中断接口,用于在 DOS 环境下执行软件中断调用

参数:

  • int intr_num :指定要执行的中断号。在 DOS 系统中,不同的中断号对应着不同的功能。例如,中断号 0x10 通常用于 BIOS 的视频服务,中断号 0x21 用于 DOS 系统功能调用。
  • union REGS *inregs :一个指向 union REGS 联合体的指针,用于传递输入参数到中断服务程序。union REGS 联合体包含了多个寄存器的成员,允许你设置不同寄存器的值,以满足特定中断服务的要求。
  • union REGS *outregs :一个指向 union REGS 联合体的指针。用于接收 DOS 中断服务程序返回的结果。当 intdosx 函数调用完成后,DOS 中断服务程序会将返回值存储在相应的寄存器中,通过 outregs 可以获取这些返回值。

union REGS 联合体:

1
2
3
4
5
6
7
8
9
10
11
12
union REGS {
struct {
unsigned char al, ah;
unsigned char bl, bh;
unsigned char cl, ch;
unsigned char dl, dh;
} h;
struct {
unsigned int ax, bx, cx, dx;
unsigned int si, di, cflag;
} x;
};

返回值: 中断服务程序执行的状态。

  • 0 表示执行成功。
  • 非零值表示执行过程中出现错误。具体的错误含义可能因中断号和中断服务程序而异。

7.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <conio.h>
#include <dos.h>

#define VIDEO 0x10

void movetoxy(int x, int y)
{
union REGS regs;

regs.h.ah = 2; /* set cursor postion */
regs.h.dh = y;
regs.h.dl = x;
regs.h.bh = 0; /* video page 0 */
int86(VIDEO, &regs, &regs);
}

int main(void)
{
clrscr();
movetoxy(35, 10);
printf("Hello\n");
return 0;
}

8. int86x

8.1 函数说明

函数声明 函数功能
int int86x(int intr_num, union REGS *insegs, union REGS *outregs, struct SREGS *segregs); 通用8086软中断接口,是一个在 DOS 环境下使用的函数,主要用于执行指定中断号的软件中断。

参数:

  • int intr_num参考7中所示
  • union REGS *inregs参考7中所示
  • union REGS *outregs参考7中所示
  • struct SREGS *segregs : 一个指向 struct SREGS 结构体的指针。
    作用:用于传递和接收段寄存器的值。struct SREGS 结构体包含了多个段寄存器成员,如 ds、es、ss 等。在某些 DOS 功能调用中,可能需要设置或获取段寄存器的值,这时就可以使用 segregs 参数。

struct SREGS 结构体:

1
2
3
4
5
6
struct SREGS {
unsigned int es;
unsigned int cs;
unsigned int ss;
unsigned int ds;
};

返回值: 中断服务程序执行的状态。

  • 0 表示执行成功。
  • 非零值表示执行过程中出现错误。具体的错误含义可能因中断号和中断服务程序而异。

8.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <dos.h>
#include <process.h>
#include <stdio.h>

int main(void)
{
char filename[80];
union REGS inregs, outregs;
struct SREGS segregs;

printf("Enter filename: ");
gets(filename);
inregs.h.ah = 0x43;
inregs.h.al = 0x21;
inregs.x.dx = FP_OFF(filename);
segregs.ds = FP_SEG(filename);
int86x(0x21, &inregs, &outregs, &segregs);
printf("File attribute: %X\n", outregs.x.cx);
return 0;
}

9. intdos

9.1 函数说明

函数声明 函数功能
int intdos(union REGS *inregs, union REGS *outregs); 执行一次 DOS 软件中断(通常是中断向量号为 0x21 的中断)

参数:

  • union REGS *inregs :一个指向 union REGS 联合体的指针。用于向 DOS 中断服务程序传递输入参数。union REGS 联合体把 8 位寄存器(如 AH、AL 等)和 16 位寄存器(如 AX、BX 等)组合在一起,方便开发者设置不同大小的寄存器值。在调用 intdos 之前,你要依据具体的 DOS 功能需求,把相应的参数存于 inregs 所指向的联合体中。
  • union REGS *outregs :一个指向 union REGS 联合体的指针。用于接收 DOS 中断服务程序返回的结果。当 intdosx 函数调用完成后,DOS 中断服务程序会将返回值存储在相应的寄存器中,通过 outregs 可以获取这些返回值。

9.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <dos.h>

/*
删除文件,成功返回0,失败返回非0。
*/
int delete_file(char near *filename)
{
union REGS regs;
int ret;
regs.h.ah = 0x41;
regs.x.dx = (unsigned) filename;
ret = intdos(&regs, &regs);

// 如果设置了进位标志,则出现错误
return(regs.x.cflag ? ret : 0);
}

int main(void)
{
int err;
err = delete_file("NOTEXIST.$$$");
if (!err)
printf("Able to delete NOTEXIST.$$$\n");
else
printf("Not Able to delete NOTEXIST.$$$\n");
return 0;
}

10. intdosx

10.1 函数说明

函数声明 函数功能
int intdosx(union REGS *inregs, union REGS *outregs, struct SREGS *segregs); 它主要作用是触发一个 DOS 软件中断(通常是中断号 0x21),并通过寄存器传递参数和获取返回值,从而实现对 DOS 系统功能的调用。

参数:

  • union REGS *inregs参考 9 中所示
  • union REGS *outregs参考 9 中所示
  • struct SREGS *segregs : 一个指向 struct SREGS 结构体的指针。
    作用:用于传递和接收段寄存器的值。struct SREGS 结构体包含了多个段寄存器成员,如 ds、es、ss 等。在某些 DOS 功能调用中,可能需要设置或获取段寄存器的值,这时就可以使用 segregs 参数。

返回值:

DOS 中断调用的状态。通常,返回值为 0 表示调用成功,非零值表示调用过程中出现错误。

10.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>
#include <dos.h>

/*
删除文件,成功返回0,失败返回非0。
*/
int delete_file(char far *filename)
{
union REGS regs;
struct SREGS sregs;
int ret;
regs.h.ah = 0x41;
regs.x.dx = FP_OFF(filename);
sregs.ds = FP_SEG(filename);
ret = intdosx(&regs, &regs, &sregs);

// 如果设置了进位标志,则出现错误
return(regs.x.cflag ? ret : 0);
}

int main(void)
{
int err;
err = delete_file("NOTEXIST.$$$");
if (!err)
printf("Able to delete NOTEXIST.$$$\n");
else
printf("Not Able to delete NOTEXIST.$$$\n");
return 0;
}

11. intr

11.1 函数说明

函数声明 函数功能
void intr(int intr_num, struct REGPACK *preg); 它是一个在早期 DOS 环境下用于进行软件中断调用的函数

参数:

  • int intr_num :要调用的中断号。在 DOSBIOS 系统中,不同的中断号对应着不同的功能。例如,中断号 0x10 通常用于 BIOS 的视频服务,中断号 0x21 用于 DOS 系统功能调用。
  • struct REGPACK *preg :这是一个指向 struct REGPACK 结构体的指针。struct REGPACK 结构体用于存储和传递 CPU 寄存器的值。在调用中断之前,你可以通过该结构体设置输入参数(即设置寄存器的值);中断调用完成后,该结构体中的值会被更新为中断服务程序返回的结果。
1
2
3
4
5
6
7
8
9
10
11
12
struct REGPACK {
unsigned r_ax;
unsigned r_bx;
unsigned r_cx;
unsigned r_dx;
unsigned r_bp;
unsigned r_si;
unsigned r_di;
unsigned r_ds;
unsigned r_es;
unsigned r_flags;
};

这个结构体包含了多个成员,分别对应不同的 CPU 寄存器。例如:

  • r_ax 对应 AX 寄存器。
  • r_bx 对应 BX 寄存器。
  • 以此类推,r_cx、r_dx 等分别对应 CX、DX 等寄存器。

11.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <string.h>
#include <dir.h>
#include <dos.h>

#define CF 1 // 进位标志

int main(void)
{
char directory[80];
struct REGPACK reg;

printf("Enter directory to change to: ");
gets(directory);
reg.r_ax = 0x3B << 8; // 将3Bh转换为AH
reg.r_dx = FP_OFF(directory);
reg.r_ds = FP_SEG(directory);
intr(0x21, &reg);
if (reg.r_flags & CF)
printf("Directory change failed\n");
getcwd(directory, 80);
printf("The current directory is: %s\n", directory);
return 0;
}

12. ioctl

12.1 函数说明

函数声明 函数功能
int ioctl(int fd, int cmd, ...) ; 控制 I/O 设备

参数:

  • fd :文件描述符
  • cmd : 交互协议,设备驱动将根据 cmd 执行对应操作
  • : 可变参数arg,依赖 cmd 指定长度以及类型

12.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <dir.h>
#include <io.h>

int main(void)
{
int stat = ioctl(0, 8, 0, 0);
if (!stat)
printf("Drive %c is removable.\n", getdisk() + 'A');
else
printf("Drive %c is not removable.\n", getdisk() + 'A');
return 0;
}

13. isatty

13.1 函数说明

函数声明 函数功能
int isatty(int handle); 用于检查给定的文件描述符(file descriptor)是否关联到一个终端设备(teletype,即 TTY)

它通常用于判断程序是否运行在交互式终端环境中,从而决定是否启用终端相关的功能(如彩色输出、交互式输入等)。

参数:

  • handle :文件描述符(file descriptor),例如:0(标准输入)1(标准输出)2(标准错误)

13.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
#include <io.h>

int main(void)
{
int handle;

handle = fileno(stdprn);
if (isatty(handle))
printf("Handle %d is a device type\n", handle);
else
printf("Handle %d isn't a device type\n", handle);
return 0;
}

13.3 运行结果

14. ilogb,ilogbf,ilogbfl

14.1 函数说明

函数声明 函数功能
int ilogb (double x); 获取 x 的对数的积分部分(double)
int ilogbf (float x); 获取 x 的对数的积分部分(float)
int ilogbl (long double x); 获取 x 的对数的积分部分(long double)

如果计算成功,则返回 x 的对数的整数部分。如果 x0,则此函数返回FP_ILOGB0 并报告错误。如果 x 是NaN值,则此函数返回 FP_ILOGBNAN 并报告错误。如果 x 是正无穷大或负无穷大,此函数将返回 INT_MAX 并报告错误。

14.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <math.h>

int main()
{
int result;
double x = 15.0;
result = ilogb(x);
printf("The integral part of the logarithm of double value %lf is %d\n", x, result);

float xf = 15.0f;
result = ilogbf(xf);
printf("The integral part of the logarithm of float value %f is %d\n", xf, result);

long double xL = 15.0L;
result = ilogbl(xL);
printf("The integral part of the logarithm of long double value %Lf is %d\n", xL, result);

return 0;
}

14.3 运行结果

15. itoa

15.1 函数说明

函数声明 函数功能
char * itoa(int value, char *string, int radix); 把一整数转换为字符串

参数:

  • value : 被转换的整数
  • string : 转换后储存的字符数组
  • radix : 转换进制数,如2,8,10,16 进制等,大小应在2-36之间

15.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int number = 12345;
char string[25];

itoa(number, string, 2);
printf("integer = %d string = %s\n", number, string);

itoa(number, string, 8);
printf("integer = %d string = %s\n", number, string);

itoa(number, string, 10);
printf("integer = %d string = %s\n", number, string);

itoa(number, string, 16);
printf("integer = %d string = %s\n", number, string);
return 0;
}

15.3 运行结果

参考

  1. [API Reference Document]
  2. [ioctl]

C语言函数大全--h开头的函数

总览

函数声明 函数功能
double hypot(double x, double y); 计算直角三角形的斜边长(double)
float hypotf (float x, float y); 计算直角三角形的斜边长(float)
long double hypot(long double x, long double y); 计算直角三角形的斜边长(long double)
#define HUGE_VAL _HUGE 正浮点常量表达式(double),这些表达式与浮点函数和运算符在溢出时返回的值相比较
#define HUGE_VALF __INFF 正浮点常量表达式(float),这些表达式与浮点函数和运算符在溢出时返回的值相比较
#define HUGE_VALL __INFL 正浮点常量表达式(long double),这些表达式与浮点函数和运算符在溢出时返回的值相比较
void harderr(int (*fptr)()); 建立一个硬件错误处理程序
void hardresume(int rescode); 硬件错误处理函数
void hardretn(int rescode); 硬件错误处理函数
void highvideo(void); 选择高亮度文本字符
int hcreate(size_t nel); 根据条目数创建哈希表。
int hcreate_r(size_t nel, struct hsearch_data *htab); 根据条目数及其描述创建哈希表。
ENTRY *hsearch(ENTRY item, ACTION action); 添加或搜索哈希条目。
int hsearch_r (ENTRY item, ACTION action, ENTRY ** retval, struct hsearch_data * htab ) 搜索哈希表。
void hdestroy(void); 销毁哈希表,释放用于创建哈希表的内存。
void hdestroy_r(struct hsearch_data *htab); 销毁哈希表,释放指定哈希表所占用的内存。

1. hypot,hypotf,hypotl

1.1 函数说明

函数声明 函数功能
double hypot(double x, double y); 计算直角三角形的斜边长(double)
float hypotf (float x, float y); 计算直角三角形的斜边长(float)
long double hypot(long double x, long double y); 计算直角三角形的斜边长(long double)

1.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <math.h>

int main(void)
{
double result, x = 3.0, y = 4.0;
result = hypot(x, y);

float resultf, xf = 3.0, yf = 4.0;
resultf = hypotf(xf, yf);

long double resultL, xL = 3.0, yL = 4.0;
resultL = hypotl(xL, yL);

printf("The hypotenuse of a right triangle whose legs are %lf and %lf is %lf\n", x, y, result);
printf("The hypotenuse of a right triangle whose legs are %f and %f is %f\n", xf, yf, resultf);
printf("The hypotenuse of a right triangle whose legs are %Lf and %Lf is %Lf\n", xL, yL, resultL);

return 0;
}

1.3 运行结果

2. HUGE_VAL,HUGE_VALF,HUGE_VALL

2.1 函数说明

宏定义 宏描述
#define HUGE_VAL _HUGE 正浮点常量表达式(double),这些表达式与浮点函数和运算符在溢出时返回的值相比较
#define HUGE_VALF __INFF 正浮点常量表达式(float),这些表达式与浮点函数和运算符在溢出时返回的值相比较
#define HUGE_VALL __INFL 正浮点常量表达式(long double),这些表达式与浮点函数和运算符在溢出时返回的值相比较

2.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<stdio.h>
#include<math.h>
int main()
{
double result = 1.0/0.0;
printf("1.0/0.0 = %lf\n", result);
if (result == HUGE_VAL)
puts("1.0/0.0 == HUGE_VAL\n");

float resultf = 1.0f/0.0f;
printf("1.0f/0.0f = %f\n", resultf);
if (resultf == HUGE_VALF)
puts("1.0f/0.0f == HUGE_VALF\n");

long double resultL = 1.0L/0.0L;
printf("1.0L/0.0L = %Lf\n", resultL);
if (resultL == HUGE_VALL)
puts("1.0L/0.0L == HUGE_VALL\n");

return 0;
}

2.3 运行结果

3. harderr,hardresume,hardretn

3.1 函数说明

函数声明 函数功能
void harderr(int (*fptr)()); 建立一个硬件错误处理程序
void hardresume(int rescode); 硬件错误处理函数
void hardretn(int rescode); 硬件错误处理函数

3.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <conio.h>
#include <dos.h>
#define IGNORE 0
#define RETRY 1
#define ABORT 2
int buf[500];

//定义捕获磁盘问题的错误消息
static char *err_msg[] = {
"write protect",
"unknown unit",
"drive not ready",
"unknown command",
"data error (CRC)",
"bad request",
"seek error",
"unknown media type",
"sector not found",
"printer out of paper",
"write fault",
"read fault",
"general failure",
"reserved",
"reserved",
"invalid disk change"
};

int error_win(char *msg)
{
int retval;
cputs(msg);

// 提示用户按键中止、重试、忽略
while(1)
{
retval= getch();
if (retval == 'a' || retval == 'A')
{
retval = ABORT;
break;
}
if (retval == 'r' || retval == 'R')
{
retval = RETRY;
break;
}
if (retval == 'i' || retval == 'I')
{
retval = IGNORE;
break;
}
}

return(retval);
}

/*
pragma warn-par 减少了由于处理程序未使用参数errval、bp 和 si而产生的警告。
*/
#pragma warn -par

int handler(int errval,int ax,int bp,int si)
{
static char msg[80];
unsigned di;
int drive;
int errorno;
di= _DI;

// 如果这不是磁盘错误,那么是另一个设备出现故障
if (ax < 0)
{
error_win("Device error");
// 返回到直接请求中止的程序
hardretn(ABORT);
}
// 否则就是磁盘错误
drive = ax & 0x00FF;
errorno = di & 0x00FF;
sprintf(msg, "Error: %s on drive %c\r\nA)bort, R)etry, I)gnore: ", err_msg[errorno], 'A' + drive);
// 通过dos中断0x23返回程序,并由用户输入中止、重试或忽略。
hardresume(error_win(msg));
return ABORT;
}

#pragma warn +par

int main(void)
{
// 在硬件问题中断上安装我们的处理程序
harderr(handler);
clrscr();
printf("Make sure there is no disk in drive A:\n");
printf("Press any key ....\n");
getch();
printf("Trying to access drive A:\n");
printf("fopen returned %p\n", fopen("A:temp.dat", "w"));
return 0;
}

上述程序是一个基于DOS环境的磁盘错误处理示例。在磁盘操作出现错误时,向用户显示具体的错误消息,并提供 “中止”“重试”“忽略” 三种处理选项,根据用户的选择进行相应的处理。

4. highvideo

4.1 函数说明

函数声明 函数功能
void highvideo(void); 选择高亮度文本字符

4.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <conio.h>

int main(void)
{
clrscr();

lowvideo();
cprintf("Low Intensity text\r\n");
highvideo();
gotoxy(1,2);
cprintf("High Intensity Text\r\n");

return 0;
}

上述利用 <conio.h> 头文件中的函数实现特定的控制台文本显示效果。

  • 首先通过 clrscr() 函数清空控制台窗口。
  • 然后调用 lowvideo() 将文本显示设置为低亮度,使用 cprintf() 输出低亮度的 "Low Intensity text" 文本并换行。
  • 接着调用 highvideo() 把文本显示切换为高亮度,利用 gotoxy(1, 2) 将光标定位到第 1 列第 2 行,再用 cprintf() 输出高亮度的 "High Intensity Text" 文本并换行,以此直观展示控制台中低亮度和高亮度两种不同的文本显示效果。

不过需要留意,conio.h 并非标准 C 库的一部分,它主要在像 Turbo C 这类旧的编译器中使用,而在现代开发环境里可能不被支持。

5. hcreate,hcreate_r

5.1 函数说明

函数声明 函数功能
int hcreate(size_t nel); 根据条目数创建哈希表。
int hcreate_r(size_t nel, struct hsearch_data *htab); 根据条目数及其描述创建哈希表。

入参:

  • net : 哈希表中允许的最大项数。
  • htab : 哈希表的结构体数据。

返回值:

  • 如果操作成功,则返回一个非零值;
  • 如果操作失败,则返回 0 并将 errno 设置为一个值。

5.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <stdlib.h>
#include <search.h>

char *data[] = { "alpha", "bravo", "charlie", "delta",
"echo", "foxtrot", "golf", "hotel", "india", "juliet",
"kilo", "lima", "mike", "november", "oscar", "papa",
"quebec", "romeo", "sierra", "tango", "uniform",
"victor", "whisky", "x-ray", "yankee", "zulu"
};

int main(void)
{
ENTRY e, *ep;
int i;

hcreate(30);

for (i = 0; i < 24; i++) {
e.key = data[i];
// 数据只是一个整数,而不是指向某个东西的指针
e.data = (void *) i;
ep = hsearch(e, ENTER);
// 这里不应该有失败场景
if (ep == NULL) {
fprintf(stderr, "entry failed\n");
exit(EXIT_FAILURE);
}
}

for (i = 22; i < 26; i++) {
// 从表中打印两个条目,并显示其中两个不在表中
e.key = data[i];
ep = hsearch(e, FIND);
printf("%9.9s -> %9.9s:%d\n", e.key, ep ? ep->key : "NULL", ep ? (int)(ep->data) : 0);
}
hdestroy();
exit(EXIT_SUCCESS);
}

6. hsearch,hsearch_r

6.1 函数说明

函数声明 函数功能
ENTRY *hsearch(ENTRY item, ACTION action); 添加或搜索哈希条目。
int hsearch_r (ENTRY item, ACTION action, ENTRY ** retval, struct hsearch_data * htab ) 搜索哈希表。

注意:
hsearchhsearch_r 函数根据指定的操作在哈希表中搜索条目。如果操作为 FIND,则仅执行搜索操作。如果操作为 ENTER,则未找到的条目将添加到哈希表中。hsearch_r 函数与 hsearch 函数的不同之处在于,指向找到的项的指针以 *retval 形式返回,而不是作为函数结果。

入参:

  • item: 要搜索的哈希表条目。
  • action: 功能操作。ENTER 表示已添加条目,FIND 表示已搜索条目。
  • retval: 指向找到的项的指针。
  • htab : 哈希表的结构体数据。

hsearch 函数返回值:

  • 如果操作成功,则返回指向哈希表的指针。

hsearch_r 函数返回值:

  • 如果操作成功,则返回一个非零值;
  • 如果操作失败,则返回 0。

6.2 演示示例

参考 5.2

7. hdestroy,hdestroy_r

7.1 函数说明

函数声明 函数功能
void hdestroy(void); 销毁哈希表,释放用于创建哈希表的内存。
void hdestroy_r(struct hsearch_data *htab); 销毁哈希表,释放指定哈希表所占用的内存。

7.2 演示示例

参考 5.2

8. htonl, htons

8.1 函数说明

函数声明 函数功能
uint32_t htonl(uint32_t hostlong); 将 uint32_t(32位整数,如IPv4地址)从主机字节序转为网络字节序。
uint16_t htons(uint16_t hostshort); 将 uint16_t(16位整数,如端口号)从主机字节序转为网络字节序(大端)。

8.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <stdint.h> // 提供 uint16_t, uint32_t 类型
#include <arpa/inet.h> // Linux/macOS 头文件(网络字节序转换)

int main() {
// 示例1:转换16位端口号(host to network short)
uint16_t host_port = 0x1234; // 主机字节序的端口(假设是小端模式)
uint16_t net_port = htons(host_port);
printf("主机端口: 0x%04x -> 网络端口: 0x%04x\n", host_port, net_port);

// 示例2:转换32位IP地址(host to network long)
uint32_t host_ip = 0x12345678; // 主机字节序的IP地址
uint32_t net_ip = htonl(host_ip);
printf("主机IP: 0x%08x -> 网络IP: 0x%08x\n", host_ip, net_ip);

return 0;
}

参考

  1. [API Reference Document]
  2. [highvideo]
  3. [hcreate,hsearch,hdestroy,hcreate_r,hsearch_r,hdestroy_r]
  4. [UTILS-标准C库]

C语言函数大全--g开头的函数(下)

总览

函数声明 函数功能
char * getmodename(int mode_name); 获取指定的图形模式名
void getmoderange(int graphdriver, int *lomode, int *himode); 获取给定图形驱动程序的模式范围
void getpalette(struct palettetype *palette); 获取有关当前调色板的信息
int getpixel(int x, int y); 获取得指定像素的颜色
char *gets(char *str); 从标准输入流中读取字符串,直至遇到到换行符或EOF时停止,并将读取的结果存放在 buffer 指针所指向的字符数组中。
换行符不作为读取串的内容,读取的换行符被转换为 '\0' 空字符,并由此来结束字符串。
void gettextsettings(struct textsettingstype *textinfo); 获取有关当前图形文本字体的信息
void getviewsettings(struct viewporttype *viewport); 获取有关当前视区的信息
int getw(FILE *strem); 从 stream 所指向文件读取下一个整数
int getx(void); 获取当前图形位置的 x 坐标
int gety(void); 获取当前图形位置的 y 坐标
struct tm *gmtime(long *clock); 把日期和时间转换为格林尼治标准时间(GMT)
void graphdefaults(void); 将所有图形设置复位为它们的缺省值
char * grapherrormsg(int errorcode); 返回一个错误信息串的指针
int graphresult(void); 返回最后一次不成功的图形操作的错误代码
int getmaxwidth(void); 获取屏幕的最大宽度
int getmaxheight(void); 获取屏幕的最大高度
int getdisplaycolor( int color ); 根据 color ,返回要显示的颜色值
int getwindowwidth(); 获取图形界面窗口宽度
int getwindowheight(void); 获取图形界面窗口高度
bool getrefreshingbgi(void); 获取刷新基础图形界面标识

1. getmodename

1.1 函数说明

函数声明 函数功能
char * getmodename(int mode_name); 获取指定的图形模式名

参数:

  • mode_name : 当前图形模式的模式代码。不同的图形模式对应不同的分辨率、颜色深度和显示模式。

1.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int midx, midy, mode;
char numname[80], modename[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

mode = getgraphmode();
sprintf(numname, "%d is the current mode number.", mode);
sprintf(modename, "%s is the current graphics mode.", getmodename(mode));

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, numname);
outtextxy(midx, midy+2*textheight("W"), modename);

getch();
closegraph();
return 0;
}

1.3 运行结果

2. getmoderange

2.1 函数说明

函数声明 函数功能
void getmoderange(int graphdriver, int *lomode, int *himode); 获取给定图形驱动程序的模式范围

参数:

  • graphdriver : 图形驱动程序的标识符。不同的图形驱动程序有不同的标识符,用于指定你希望使用的图形硬件或软件环境。例如,在某些图形库中,特定的数字或宏定义(如DETECT)可以用来自动检测可用的图形驱动程序。
  • lomode : 一个指向整数的指针,用于接收指定图形驱动程序支持的最低显示模式编号。
  • himode : 一个指向整数的指针,用于接收指定图形驱动程序支持的最高显示模式编号。

2.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
int gdriver = DETECT, gmode, errorcode;
int midx, midy, low, high;
char mrange[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

getmoderange(gdriver, &low, &high);

sprintf(mrange, "This driver supports modes %d~%d", low, high);

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, mrange);

getch();
closegraph();
return 0;
}

2.3 运行结果

3. getpalette

3.1 函数说明

函数声明 函数功能
void getpalette(struct palettetype *palette); 获取有关当前调色板的信息

参数:

  • palette : 一个指向palettetype结构体的指针。palettetype结构体通常包含了一系列元素,每个元素代表调色板中的一个颜色条目。在标准的图形库中(如BorlandBGI图形库),palettetype结构体可能包含多个unsigned char类型的成员,每个成员对应调色板中的一个颜色通道(如红色、绿色、蓝色),以及可能的其他信息(如亮度或透明度)。

注意: palettetype结构体的确切定义可能依赖于你使用的图形库。在某些实现中,它可能是一个简单的数组,每个元素代表一个颜色(可能是RGB值的一个组合),或者是一个更复杂的结构体,包含了关于每个颜色条目的更多信息。

3.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
int gdriver = DETECT, gmode, errorcode;
struct palettetype pal;
char psize[80], pval[20];
int i, ht;
int y = 10;

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

getpalette(&pal);

sprintf(psize, "The palette has %d modifiable entries.", pal.size);

outtextxy(0, y, psize);
if (pal.size != 0)
{
ht = textheight("W");
y += 2*ht;
outtextxy(0, y, "Here are the current values:");
y += 2*ht;
for (i=0; i < pal.size; i++, y+=ht)
{
sprintf(pval, "palette[%02d]: 0x%02X", i, pal.colors[i]);
outtextxy(0, y, pval);
}
}

getch();
closegraph();
return 0;
}

3.3 运行结果

4. getpixel

4.1 函数说明

函数声明 函数功能
int getpixel(int x, int y); 获取得指定像素的颜色

参数:

  • x : 想要获取的像素颜色值的点的横坐标。坐标原点(0, 0)通常位于屏幕的左上角。
  • y : 想要获取的像素颜色值的点的纵坐标。

返回值:

函数返回一个整数,该整数代表指定坐标 (x, y) 上像素的颜色编码。颜色编码的具体含义取决于你使用的图形库和当前的图形设置。在某些图形库中,这个整数可能直接代表一个RGB颜色值,其中不同的位或字节表示红色、绿色和蓝色通道的强度。在其他情况下,这个整数可能是一个索引值,指向当前调色板中的一个颜色条目。

4.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define PIXEL_COUNT 1000
#define DELAY_TIME 100

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int midx, midy, x, y, color, maxx, maxy, maxcolor;
char mPixel[50];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

maxx = getmaxx() + 1;
maxy = getmaxy() + 1;
maxcolor = getmaxcolor() + 1;

while (!kbhit())
{
srand((unsigned)time(NULL));
x = rand() % maxx;
y = rand() % maxy;
color = rand() % maxcolor;
putpixel(x, y, color);

sprintf(mPixel, "color of pixel at (%d,%d) = %d", x, y, getpixel(x, y));
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, mPixel);

delay(DELAY_TIME);

cleardevice();
}

getch();
closegraph();
return 0;
}

4.3 运行结果

5. gets

5.1 函数说明

函数声明 函数功能
char *gets(char *str); 从标准输入流中读取字符串,直至遇到到换行符或EOF时停止,并将读取的结果存放在 buffer 指针所指向的字符数组中。
换行符不作为读取串的内容,读取的换行符被转换为 '\0' 空字符,并由此来结束字符串。

注意: gets 函数可以无限读取,易发生溢出。如果溢出,多出来的字符将被写入到堆栈中,这就覆盖了堆栈原先的内容,破坏一个或多个不相关变量的值。

5.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main()
{
char string[80];

printf("Input a string:");
gets(string);
printf("The string input was: %s\n", string);
return 0;
}

5.3 运行结果

6. gettextsettings

6.1 函数说明

函数声明 函数功能
void gettextsettings(struct textsettingstype *textinfo); 获取有关当前图形文本字体的信息

参数:

  • textinfo : 一个指向 textsettingstype 结构体的指针。该结构体用于存储当前的文本设置。textsettingstype 结构体的具体定义取决于你使用的图形库。在不同的图形库中,这个结构体可能包含不同的成员,以反映该库支持的文本设置选项。

6.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

// 文本字体
char *font[] = { "DEFAULT_FONT",
"TRIPLEX_FONT",
"SMALL_FONT",
"SANS_SERIF_FONT",
"GOTHIC_FONT"
};

// 文本方向
char *dir[] = { "HORIZ_DIR", "VERT_DIR" };

// 文本水平对齐方式
char *hjust[] = { "LEFT_TEXT", "CENTER_TEXT", "RIGHT_TEXT" };

// 文本垂直对齐方式
char *vjust[] = { "BOTTOM_TEXT", "CENTER_TEXT", "TOP_TEXT" };

int main()
{
int gdriver = DETECT, gmode, errorcode;
struct textsettingstype textinfo;
int midx, midy, ht;
char fontstr[80], dirstr[80], sizestr[80];
char hjuststr[80], vjuststr[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

// 获取有关当前图形文本字体的信息
gettextsettings(&textinfo);

sprintf(fontstr, "%s is the text style.", font[textinfo.font]);
sprintf(dirstr, "%s is the text direction.", dir[textinfo.direction]);
sprintf(sizestr, "%d is the text size.", textinfo.charsize);
sprintf(hjuststr, "%s is the horizontal justification.", hjust[textinfo.horiz]);
sprintf(vjuststr, "%s is the vertical justification.", vjust[textinfo.vert]);

ht = textheight("W");
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, fontstr);
outtextxy(midx, midy+2*ht, dirstr);
outtextxy(midx, midy+4*ht, sizestr);
outtextxy(midx, midy+6*ht, hjuststr);
outtextxy(midx, midy+8*ht, vjuststr);

getch();
closegraph();
return 0;
}

6.3 运行结果

7. getviewsettings

7.1 函数说明

函数声明 函数功能
void getviewsettings(struct viewporttype *viewport); 获取有关当前视区的信息

参数:

  • viewport : 一个指向 viewporttype 结构体的指针。该结构体用于存储当前的视口设置。调用 getviewsettings 函数后,这个结构体将被填充为当前的视口参数。 viewporttype 结构体的具体定义可能依赖于你使用的图形库,但通常它会包含以下成员:
    • left, top: 这两个成员定义了视口的左上角坐标。坐标原点通常位于屏幕的左上角。
    • right, bottom: 这两个成员定义了视口的右下角坐标。
    • clip: 一个用于指示视口是否启用裁剪的标志。如果启用了裁剪,那么任何在视口之外的图形输出都将被忽略。

7.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

char *clip[] = { "OFF", "ON" };

int main()
{
int gdriver = DETECT, gmode, errorcode;
struct viewporttype viewinfo;
int midx, midy, ht;
char topstr[80], botstr[80], clipstr[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

// 获取有关当前视区的信息
getviewsettings(&viewinfo);

sprintf(topstr, "(%d, %d) is the upper left viewport corner.", viewinfo.left, viewinfo.top);
sprintf(botstr, "(%d, %d) is the lower right viewport corner.", viewinfo.right, viewinfo.bottom);
sprintf(clipstr, "Clipping is turned %s.", clip[viewinfo.clip]);

settextjustify(CENTER_TEXT, CENTER_TEXT);
ht = textheight("W");
outtextxy(midx, midy, topstr);
outtextxy(midx, midy+2*ht, botstr);
outtextxy(midx, midy+4*ht, clipstr);

getch();
closegraph();
return 0;
}

7.3 运行结果

8. getw

8.1 函数说明

函数声明 函数功能
int getw(FILE *strem); 从 stream 所指向文件读取下一个整数

8.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <stdlib.h>

#define FNAME "test.txt"

int main(void)
{
FILE *fp;
int word;

fp = fopen(FNAME, "wb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}

word = 94;
putw(word,fp);
if (ferror(fp))
printf("Error writing to file\n");
else
printf("Successful write\n");
fclose(fp);

fp = fopen(FNAME, "rb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}

word = getw(fp);
if (ferror(fp))
printf("Error reading file\n");
else
printf("Successful read: word = %d\n", word);

fclose(fp);
unlink(FNAME);

return 0;
}

8.3 运行结果

9. getx,gety

9.1 函数说明

函数声明 函数功能
int getx(void); 获取当前图形位置的 x 坐标
int gety(void); 获取当前图形位置的 y 坐标

9.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
char msg[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

moveto(getmaxx() / 2, getmaxy() / 2);

sprintf(msg, "<-(%d, %d) is the here.", getx(), gety());

outtext(msg);

getch();
closegraph();
return 0;
}

9.3 运行结果

10. gmtime

10.1 函数说明

函数声明 函数功能
struct tm *gmtime(long *clock); 把日期和时间转换为格林尼治标准时间(GMT)

10.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <dos.h>

// 太平洋标准时间和夏令时
char *tzstr = "TZ=PST8PDT";

int main(void)
{
time_t t;
struct tm *gmt, *area;
putenv(tzstr); // 用来改变或增加环境变量的内容
tzset(); // UNIX时间兼容函数
// 获取当前的系统时间,其值表示从协调世界时(Coordinated Universal Time)
// 1970年1月1日00:00:00(称为UNIX系统的Epoch时间)到当前时刻的秒数。
t = time(NULL);
area = localtime(&t); // 把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间
// asctime 把timeptr指向的tm结构体中储存的时间转换为字符串
printf("Local time is: %s", asctime(area));
// 把日期和时间转换为格林尼治标准时间(GMT)
gmt = gmtime(&t);
printf("GMT is: %s", asctime(gmt));
return 0;
}

10.3 运行结果

11. graphdefaults

11.1 函数说明

函数声明 函数功能
void graphdefaults(void); 将所有图形设置复位为它们的缺省值

11.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;

initgraph(&gdriver, &gmode, "c:\\bor\\Borland\\bgi");
errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

maxx = getmaxx();
maxy = getmaxy();

setlinestyle(DOTTED_LINE, 0, 3);
line(0, 0, maxx, maxy);
outtextxy(maxx/2, maxy/3, "Before default values are restored.");
getch();

// 将所有图形设置复位为它们的缺省值
graphdefaults();

cleardevice();

line(0, 0, maxx, maxy);
outtextxy(maxx/2, maxy/3, "After restoring default values.");

getch();
closegraph();
return 0;
}

11.3 运行结果

12. grapherrormsg

12.1 函数说明

函数声明 函数功能
char * grapherrormsg(int errorcode); 返回一个错误信息串的指针

12.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

#define NONSENSE -50

int main(void)
{
// FORCE AN ERROR TO OCCUR
int gdriver = NONSENSE, gmode, errorcode;

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();

if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

line(0, 0, getmaxx(), getmaxy());

getch();
closegraph();
return 0;
}

12.3 运行结果

13. graphresult

13.1 函数说明

函数声明 函数功能
int graphresult(void); 返回最后一次不成功的图形操作的错误代码

13.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
// request auto detection
int gdriver = DETECT, gmode, errorcode;

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

line(0, 0, getmaxx(), getmaxy());

getch();
closegraph();
return 0;
}

13.3 运行结果

14. getmaxwidth,getmaxheight

14.1 函数说明

函数声明 函数功能
int getmaxwidth(void); 获取屏幕的最大宽度
int getmaxheight(void); 获取屏幕的最大高度

14.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
char ch[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

sprintf(ch, "maxwidth = %d, maxheight = %d", getmaxwidth(), getmaxheight());

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, ch);

getch();
closegraph();
return 0;
}

14.3 运行结果

15. getdisplaycolor

15.1 函数说明

函数声明 函数功能
int getdisplaycolor( int color ); 根据 color ,返回要显示的颜色值

注意: color = -1 , 则返回 WHITE = 15 的颜色值;color < - 1 或 color > 15,则输出一个8位整数。

15.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
char ch[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

sprintf(ch, "color = %d, displaycolor(-1) = %d, displaycolor(16) = %d", getcolor(), getdisplaycolor(-1), getdisplaycolor(16));

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, ch);

getch();
closegraph();
return 0;
}

15.3 运行结果

16. getwindowwidth,getwindowheight

16.1 函数说明

函数声明 函数功能
int getwindowwidth(void); 获取图形界面窗口宽度
int getwindowheight(void); 获取图形界面窗口高度

16.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
int gdriver = DETECT, gmode, errorcode;
int midx, midy, low, high;
char ch[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

sprintf(ch, "windowwidth = %d, windowheight = %d", getwindowwidth(), getwindowheight());

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, ch);

getch();
closegraph();
return 0;
}

16.3 运行结果

17. getrefreshingbgi

17.1 函数说明

函数声明 函数功能
bool getrefreshingbgi(void); 获取刷新基础图形界面标识

17.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
int gdriver = DETECT, gmode, errorcode;
int midx, midy, low, high;
char ch[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

sprintf(ch, "refreshingbgi = %d", getrefreshingbgi());

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, ch);

getch();
closegraph();
return 0;
}

17.3 运行结果

参考

  1. [API Reference Document]
  2. [gets]

C语言函数大全--g开头的函数(上)

总览

函数声明 函数功能
char *gcvt(double value, int ndigit, char *buf); 把浮点数转换成字符串,同时返回一个指向字符串的存储位置的指针的函数。
void getarccoords(struct arccoordstype *arccoords); 取最后一次调用arc的坐标
int getbkcolor(void); 获取当前背景颜色
int getc(FILE *stream); 从流中取字符
int getchar(void); stdin 流中读字符
int getcolor(void); 当前画线的颜色
char *getcwd(char *buffer, int maxlen); 获取当前工作目录
struct palettetype* getdefaultpalette(void); 获取调色板定义结构
char *getdrivename(void); 获取当前图形驱动程序名字
void getfillpattern(char *upattern); 将用户定义的填充模式拷贝到内存中
void getfillsettings(struct fillsettingstype *fillinfo); 获取有关当前填充模式和填充颜色的信息
int getgraphmode(void); 获取当前图形模式
void getimage(int left, int top, int right, int bottom, void *bitmap); 保存指定区域的屏幕上的像素图形到指定的内存区域
void getlinesettings(struct linesettingstype *lininfo); 取当前线型、模式和宽度
int getmaxcolor(void); 可以传给函数 setcolor 的最大颜色值
int getmaxx(void); 屏幕的最大x坐标
int getmaxy(void); 屏幕的最大y坐标

1. gcvt

1.1 函数说明

函数声明 函数功能
char *gcvt(double value, int ndigit, char *buf); 把浮点数转换成字符串,同时返回一个指向字符串的存储位置的指针的函数。

参数:

  • value: 被转换的值。
  • ndigit: 存储的有效数字位数。
  • buf: 结果的存储位置。

注意: gcvt 函数把一个浮点值转换成一个字符串 (包括一个小数点和可能的符号字节) 并存储该字符串在 buffer 中。该 buffer 应足够大以便容纳转换的值加上结尾的 结束符 '\0',它是自动添加的。
如果一个缓冲区的大小为 ndigit + 1,则 gcvt 函数将覆盖该缓冲区的末尾。这是因为转换的字符串包括一个小数点以及可能包含符号和指数信息。

1.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
char str[25];
double num;
int sig = 5;

num = 1.23;
gcvt(num, sig, str);
printf("string = %s\n", str);

num = -456.78912;
gcvt(num, sig, str);
printf("string = %s\n", str);

num = 0.345e5;
gcvt(num, sig, str);
printf("string = %s\n", str);

return(0);
}

1.3 运行结果

2. getarccoords

2.1 函数说明

函数声明 函数功能
void getarccoords(struct arccoordstype *arccoords); 取最后一次调用arc的坐标

2.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main()
{
int gdriver = DETECT, gmode, errorcode;
struct arccoordstype arcinfo;
int midx, midy;
int stangle = 45, endangle = 270;
char sstr[80], estr[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

setcolor(getmaxcolor());
arc(midx, midy, stangle, endangle, 100);
// 取最后一次调用arc的坐标
getarccoords(&arcinfo);

sprintf(sstr, "*- (%d, %d)", arcinfo.xstart, arcinfo.ystart);
sprintf(estr, "*- (%d, %d)", arcinfo.xend, arcinfo.yend);

outtextxy(arcinfo.xstart, arcinfo.ystart, sstr);
outtextxy(arcinfo.xend, arcinfo.yend, estr);

getch();
closegraph();
return 0;
}

上述代码是一个简单的图形程序,使用了图形库函数 arc 来绘制一个弧线并显示其起始和结束点的坐标。

大致逻辑如下:

  1. 初始化图形驱动和模式,创建一个空的图形窗口。
  2. 检查图形操作是否成功,如果失败则输出错误信息并退出程序。
  3. 计算屏幕的中心点坐标 (midx, midy)
  4. 设置绘图颜色为最大颜色值。
  5. 在屏幕中心绘制一个弧线,起始角度为 45 度,结束角度为 270 度,半径为 100 像素。
  6. 获取最后一次调用 arc 函数时的坐标信息,并将其存储在 arcinfo 结构体中。
  7. 使用 sprintf 函数将起始点和结束点的坐标格式化为字符串。
  8. 在屏幕上显示起始点和结束点的坐标信息。
  9. 等待用户按键输入,然后关闭图形窗口并退出程序。

2.3 运行结果

3. getbkcolor

3.1 函数说明

函数声明 函数功能
int getbkcolor(void); 获取当前背景颜色
颜色值 英文枚举 中文描述
0 BLACK
1 BLUE
2 GREEN 绿
3 CYAN
4 RED
5 MAGENTA 洋红
6 BROWN
7 LIGHTGRAY 淡灰
8 DARKGRAY 深灰
9 LIGHTBLUE 淡兰
10 LIGHTGREEN 淡绿
11 LIGHTCYAN 淡青
12 LIGHTRED 淡红
13 LIGHTMAGENTA 淡洋红
14 YELLOW
15 WHITE

3.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <graphics.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int bkcolor, midx, midy;
char bkname[35];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());

settextjustify(CENTER_TEXT, CENTER_TEXT);
cleardevice();

for (int i = WHITE; i >= 0; i--)
{
setbkcolor(i);
bkcolor = getbkcolor(); // 获取当前背景颜色
if (i == WHITE) setcolor(BLACK);
else setcolor(WHITE);
itoa(bkcolor, bkname, 10);
strcat(bkname," is the current background color.");

outtextxy(midx, midy, bkname);
getch();
cleardevice();
}

getch();
closegraph();
return 0;
}

上述也是一个简单的图形程序,通过使用图形库来绘制背景颜色变化。

下面来简单总结下:

  1. 初始化图形驱动和模式,创建一个空的图形窗口。
  2. 检查图形操作是否成功,如果失败则输出错误信息并退出程序。
  3. 计算屏幕的中心点坐标 (midx, midy)
  4. 设置绘图颜色为最大颜色值。
  5. 设置文本对齐方式为中心对齐。
  6. 清空设备上的图形内容。
  7. 循环遍历从白色到黑色的背景颜色,每次循环执行以下操作:
  • 设置当前背景颜色为循环变量 i 所代表的颜色。
  • 获取当前背景颜色并将其转换为字符串形式存储在 bkcolor 数组中。
  • 如果当前颜色是白色,则设置文本颜色为黑色;否则设置为白色。
  • 将背景颜色信息添加到 bkname 字符串中。
  • 在屏幕中心位置显示包含背景颜色信息的文本。
  • 等待用户按键输入,然后清空设备上的图形内容。
  1. 等待用户按键输入,然后关闭图形窗口并退出程序。

3.3 运行结果

4. getc

4.1 函数说明

函数声明 函数功能
int getc(FILE *stream); 从流中取字符

4.2 演示示例

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main()
{
char ch;
printf("Input a character:");
ch = getc(stdin);
printf("The character input was: '%c'\n", ch);
return 0;
}

4.3 运行结果

5. getchar

5.1 函数说明

函数声明 函数功能
int getchar(void); stdin 流中读字符

5.2 演示示例

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main(void)
{
int c;
while ((c = getchar()) != '\n')
printf("%c ", c);

return 0;
}

5.3 运行结果

6. getcolor

6.1 函数说明

函数声明 函数功能
int getcolor(void); 当前画线的颜色
颜色值 英文枚举 中文描述
0 BLACK
1 BLUE
2 GREEN 绿
3 CYAN
4 RED
5 MAGENTA 洋红
6 BROWN
7 LIGHTGRAY 淡灰
8 DARKGRAY 深灰
9 LIGHTBLUE 淡兰
10 LIGHTGREEN 淡绿
11 LIGHTCYAN 淡青
12 LIGHTRED 淡红
13 LIGHTMAGENTA 淡洋红
14 YELLOW
15 WHITE

6.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <graphics.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int color, midx, midy;
char colname[35];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
/* an error occurred */
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());

settextjustify(CENTER_TEXT, CENTER_TEXT);

for (int i = WHITE; i > 0; i--)
{
color = getcolor();
itoa(color, colname, 10);
strcat(colname, " is the current drawing color.");
outtextxy(midx, midy, colname);
getch();
cleardevice();
setcolor(i - 1);
}

getch();
closegraph();
return 0;
}

上述程序,通过使用图形库,在一个循环中遍历所有颜色,每次在屏幕中心显示当前颜色的名称和值,等待用户按键后更改颜色并清除屏幕,直到所有颜色展示完毕。

6.3 运行结果

7. getcwd

7.1 函数说明

函数声明 函数功能
char *getcwd(char *buffer, int maxlen); 获取当前工作目录

注意:getcwd 函数是将当前工作目录的绝对路径复制到参数 buffer 所指的内存空间中,参数 maxlenbuffer 的空间大小。

7.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <dir.h>

#define MAXPATH 1000

int main()
{
char buffer[MAXPATH];
getcwd(buffer, MAXPATH);
printf("The current directory is: %s\n", buffer);
return 0;
}

7.3 运行结果

8. getdefaultpalette

8.1 函数说明

函数声明 函数功能
struct palettetype* getdefaultpalette(void); 获取调色板定义结构

8.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int i, midx, midy;;

struct palettetype far *pal=NULL;

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 3;
midy = getmaxy() / 2;
setcolor(getmaxcolor());
// 获取调色板定义结构
pal = getdefaultpalette();

char buffer[100];
for (i=BLACK; i<WHITE + 1; i++)
{
sprintf(buffer, "colors[%d] = %d", i, pal->colors[i]);
outtextxy(midx, midy, buffer);
getch();
cleardevice();
}

getch();
closegraph();
return 0;
}

8.3 运行结果

9. getdrivername

9.1 函数说明

函数声明 函数功能
char *getdrivename(void); 获取当前图形驱动程序名字

9.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
char *drivername;
initgraph(&gdriver, &gmode, "");
errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

setcolor(getmaxcolor());

// 当前图形驱动程序名字
drivername = getdrivername();

settextjustify(CENTER_TEXT, CENTER_TEXT);

outtextxy(getmaxx() / 2, getmaxy() / 2, drivername);

getch();
closegraph();
return 0;
}

9.3 运行结果

10. getfillpattern

10.1 函数说明

函数声明 函数功能
void getfillpattern(char *upattern); 将用户定义的填充模式拷贝到内存中

10.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <graphics.h>
#include <stdio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;
char pattern[8] = {0x00, 0x70, 0x20, 0x27, 0x25, 0x27, 0x04, 0x04};

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

maxx = getmaxx();
maxy = getmaxy();
setcolor(getmaxcolor());
// 选择用户定义的填充模式
setfillpattern(pattern, getmaxcolor());

bar(0, 0, maxx, maxy);

getch();
// 将用户定义的填充模式拷贝到内存中
getfillpattern(pattern);

pattern[0] += 1;
pattern[1] -= 2;
pattern[2] += 3;
pattern[3] -= 4;
pattern[4] += 5;
pattern[5] -= 6;
pattern[6] += 7;
pattern[7] -= 8;
// 选择用户定义的填充模式
setfillpattern(pattern, getmaxcolor());

bar(0, 0, maxx, maxy);

getch();
closegraph();
return 0;
}

10.3 运行结果

11. getfillsettings

11.1 函数说明

函数声明 函数功能
void getfillsettings(struct fillsettingstype *fillinfo); 获取有关当前填充模式和填充颜色的信息

参数:

  • struct fillsettingstype *fillinfo : 一个指向 fillsettingstype 结构体的指针,该结构体用于存储当前的填充模式设置。 fillsettingstype 结构体通常包含以下成员:
    • int pattern:指定填充图案的索引。 BGI库提供了一套预定义的填充图案,可以通过这个索引来选择。
    • unsigned char color:指定填充图案的颜色。 颜色通常是通过一个颜色索引来指定的,该索引对应于一个预定义的颜色表。

11.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

// the names of the fill styles supported
char *fname[] = { "EMPTY_FILL",
"SOLID_FILL",
"LINE_FILL",
"LTSLASH_FILL",
"SLASH_FILL",
"BKSLASH_FILL",
"LTBKSLASH_FILL",
"HATCH_FILL",
"XHATCH_FILL",
"INTERLEAVE_FILL",
"WIDE_DOT_FILL",
"CLOSE_DOT_FILL",
"USER_FILL"
};

int main()
{
int gdriver = DETECT, gmode, errorcode;
struct fillsettingstype fillinfo;
int midx, midy;
char patstr[40], colstr[40];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

// 获取有关当前填充模式和填充颜色的信息
getfillsettings(&fillinfo);

sprintf(patstr, "%s is the fill style.", fname[fillinfo.pattern]);
sprintf(colstr, "%d is the fill color.", fillinfo.color);

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, patstr);
outtextxy(midx, midy+2*textheight("W"), colstr);

getch();
closegraph();
return 0;
}

11.3 运行结果

12. getgraphmode

12.1 函数说明

函数声明 函数功能
int getgraphmode(void); 获取当前图形模式

12.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <graphics.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int midx, midy, mode;
char numname[80], modename[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

// 获取当前图形模式
mode = getgraphmode();
sprintf(numname, "%d is the current mode number.", mode);
sprintf(modename, "%s is the current graphics mode", getmodename(mode));

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, numname);
outtextxy(midx, midy+2*textheight("W"), modename);

getch();
closegraph();
return 0;
}

12.3 运行结果

13. getimage

13.1 函数说明

函数声明 函数功能
void getimage(int left, int top, int right, int bottom, void *bitmap); 保存指定区域的屏幕上的像素图形到指定的内存区域

参数:

  • int left:指定要获取的图像区域的左边界的x坐标,以像素为单位
  • int top: 指定要获取的图像区域的上边界的y坐标,以像素为单位
  • int right: 指定要获取的图像区域的右边界的x坐标,以像素为单位
  • int bottom:指定要获取的图像区域的下边界的y坐标,以像素为单位
  • void *bitmap: 指向存储获取到的图像数据的内存位置的指针,这个指针可以指向任何类型的数据。在实际使用中,这个指针通常指向一个预先分配好的缓冲区,该缓冲区的大小应足够存储指定区域的图像数据。

13.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<graphics.h>
int main()
{
int driver,mode;
unsigned size;
void *buf;

driver=DETECT;
mode=0; initgraph(&driver,&mode,"");

setcolor(15);
rectangle(20,20,200,200);

setcolor(RED);
line(20,20,200,200);

setcolor(GREEN);
line(20,200,200,20);

getch();

size=imagesize(20,20,200,200);
if(size!=-1)
{
buf=malloc(size);
if(buf)
{
getimage(20,20,200,200,buf);
putimage(100,100, buf,COPY_PUT);
putimage(300,50, buf,COPY_PUT);
}
}
outtext("press a key");
getch();
return 0;
}

13.3 运行结果

14. getlinesettings

14.1 函数说明

函数声明 函数功能
void getlinesettings(struct linesettingstype *lininfo); 取当前线型、模式和宽度

参数:

  • struct linesettingstype *lininfo : 一个指向 linesettingstype 结构体的指针,该结构体用于存储当前的线条绘制设置。linesettingstype 结构体通常包含以下成员:
    • int linestyle: 指定线条的类型。它通常是一个整数,用于选择预定义的线条样式,如实线、虚线、点线等。
    • unsigned char upattern: 对于某些线条样式(如虚线),该参数可能用于指定线条中点和空白的具体模式。
    • int thickness: 指定线条的宽度。在BGI中,线条的宽度可能是以像素为单位的,但具体实现可能有所不同。
    • unsigned char color: 指定线条的颜色。颜色通常是通过一个颜色索引来指定的,该索引对应于一个预定义的颜色表。

14.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

// the names of the line styles supported
char *lname[] = { "SOLID_LINE",
"DOTTED_LINE",
"CENTER_LINE",
"DASHED_LINE",
"USERBIT_LINE"
};

int main()
{
int gdriver = DETECT, gmode, errorcode;
struct linesettingstype lineinfo;
int midx, midy;
char lstyle[80], lpattern[80], lwidth[80];

initgraph(&gdriver, &gmode, "");
errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

// 取当前线型、模式和宽度
getlinesettings(&lineinfo);

sprintf(lstyle, "%s is the line style.", lname[lineinfo.linestyle]);
sprintf(lpattern, "0x%X is the user-defined line pattern.", lineinfo.upattern);
sprintf(lwidth, "%d is the line thickness.", lineinfo.thickness);

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, lstyle);
outtextxy(midx, midy+2*textheight("W"), lpattern);
outtextxy(midx, midy+4*textheight("W"), lwidth);

getch();
closegraph();
return 0;
}

14.3 运行结果

15. getmaxcolor

15.1 函数说明

函数声明 函数功能
int getmaxcolor(void); 可以传给函数 setcolor 的最大颜色值

15.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
char colstr[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

sprintf(colstr, "This mode supports colors 0~%d", getmaxcolor());

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, colstr);

getch();
closegraph();
return 0;
}

15.3 运行结果

16. getmaxx,getmaxy

16.1 函数说明

函数声明 函数功能
int getmaxx(void); 屏幕的最大x坐标
int getmaxy(void); 屏幕的最大y坐标

16.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
char xrange[80], yrange[80];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;

sprintf(xrange, "X values range from 0~%d", getmaxx());
sprintf(yrange, "Y values range from 0~%d", getmaxy());

settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(midx, midy, xrange);
outtextxy(midx, midy+2*textheight("W"), yrange);

getch();
closegraph();
return 0;
}

16.3 运行结果

参考

  1. [API Reference Document]

C语言函数大全--f开头的函数(下)

总览

函数声明 函数功能
double floor (double x); 获取小于或等于 x 的最大整数(double)。
float floorf (float x); 获取小于或等于 x 的最大整数(float)。
long double floorl (long double x) 获取小于或等于 x 的最大整数(long double)。
int _flushall(void); 清除所有缓冲区,返回打开的流(输入和输出)的数量
double fma (double x, double y, double z); 计算x*y+z的值,并将结果四舍五入(double)。
float fmaf (float x, float y, float z ); 计算x*y+z的值,并将结果四舍五入(float )。
long double fmal (long double x, long double y, long double z); 计算x*y+z的值,并将结果四舍五入(double)。
double fmax (double x, double y); 获取 x 和 y 中的最大值(double)
float fmaxf (float x, float y); 获取 x 和 y 中的最大值(float)
long double fmaxl (long double x, long double y); 获取 x 和 y 中的最大值(long double)
double fmin (double x, double y); 获取 x 和 y 中的最小值(double)
float fminf (float x, float y); 获取 x 和 y 中的最小值(float)
long double fminl (long double x, long double y); 获取 x 和 y 中的最小值(long double)
double fmod (double x, double y); 计算 x 除以 y 的余数(double)。
float fmodf (float x, float y); 计算 x 除以 y 的余数(float)。
long double fmodl (long double x, long double y); 计算 x 除以 y 的余数(long double)。
FILE *fopen(const char *filename, const char *mode); 使用给定的模式mode打开filename所指向的文件。
int fprintf(FILE *stream, char *format[, argument,...]); 格式化输出到一个流文件中
int fputc(int ch, FILE *stream); 将字符【ch为字符的ascii码】写到文件指针stream所指向的文件的当前写指针的位置
int fputchar(char ch); 送一个字符到标准输出流(stdout)中,出错则返回EOF
int fputs(const char *str, FILE *stream); 把字符串写入到指定的流( stream) 中,但不包括空字符。
int fread(void *buffer, int size, int count, FILE *stream); 从给定输入流stream读取最多count个对象到数组buffer中
void free(void *ptr); 释放ptr指向的存储空间
FILE * freopen(const char *filename, const char *mode, FILE *stream); 以指定模式重新指定到另一个文件
double frexp (double x, int * exp); 将x 分解为有效位 和 2 的整数指数。(double)。
float frexpf (float x, int * exp); 将x 分解为有效位 和 2 的整数指数。(float)。
long double frexpl (long double x, int * exp); 将x 分解为有效位 和 2 的整数指数。(long double)。
int fscanf(FILE *stream, char *format[,argument...]); 从一个流中执行格式化输入
int fseek(FILE *stream, long offset, int fromwhere); 重定位流上的文件指针位置
int fsetpos(FILE *stream, const fpos_t *pos); 将文件指针定位在pos指定的位置上。如果成功返回0,否则返回非0。
int fstat(int handle,struct stat *buf); 由文件描述符获取文件状态
long ftell(FILE *stream); 获取文件指针当前位置相对于文件首的偏移字节数
int fwrite(const void *ptr, int size, int nitems, FILE *stream); 把ptr所指向的数组中的数据写入到给定流stream中

1. floor,floorf,floorl

1.1 函数说明

函数声明 函数功能
double floor (double x); 获取小于或等于 x 的最大整数(double)。
float floorf (float x); 获取小于或等于 x 的最大整数(float)。
long double floorl (long double x) 获取小于或等于 x 的最大整数(long double)。

1.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>
#include<math.h>

int main()
{
double x = 10.24;
printf("floor(%.2lf) = %.2lf\n", x, floor(x));

float xf = 5.63;
printf("floorf(%.2f) = %.2f\n", xf, floorf(xf));

long double xL = 2.89;
printf("floorl(%.2Lf) = %.2Lf\n", xL, floorl(xL));
return 0;
}

1.3 运行结果

2. _flushall

2.1 函数说明

函数声明 函数功能
int _flushall(void); 清除所有缓冲区,返回打开的流(输入和输出)的数量

2.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main()
{
FILE *stream = fopen("STU.FIL", "w");
// 清除所有缓冲区
// 返回打开的流(输入和输出)的数量
printf("%d streams were flushed.\n", _flushall());
fclose(stream);
return 0;
}

2.3 运行结果

3. fma,fmaf,fmal

3.1 函数说明

函数声明 函数功能
double fma (double x, double y, double z); 计算x*y+z的值,并将结果四舍五入(double)。
float fmaf (float x, float y, float z ); 计算x*y+z的值,并将结果四舍五入(float )。
long double fmal (long double x, long double y, long double z); 计算x*y+z的值,并将结果四舍五入(double)。

3.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <math.h>

int main() {

double x = 2.0, y = 3.0, z = 4.0;
float xf = 2.0, yf = 3.0, zf = 4.0;
long double xL = 2.0, yL = 3.0, zL = 4.0;

printf("fma(%lf, %lf, %lf) = %lf\n", x, y, z, fma(x, y, z));
printf("fmaf(%f, %f, %f) = %f\n", xf, yf, zf, fmaf(xf, yf, zf));
printf("fmal(%Lf, %Lf, %Lf) = %Lf\n", xL, yL, zL, fmal(xL, yL, zL));

return 0;
}

3.3 运行结果

4. fmax,fmaxf,fmaxl

4.1 函数说明

函数声明 函数功能
double fmax (double x, double y); 获取 x 和 y 中的最大值(double)
float fmaxf (float x, float y); 获取 x 和 y 中的最大值(float)
long double fmaxl (long double x, long double y); 获取 x 和 y 中的最大值(long double)

4.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>
#include<math.h>

int main()
{
double x = 10.24, y = 5.63;
printf("fmax(%.2lf, %.2lf) = %.2lf\n", x, y, fmax(x, y));

float xf = 5.63, yf = 2.89;
printf("fmaxf(%.2f, %.2f) = %.2f\n", xf, yf, fmaxf(xf, yf));

long double xL = 2.89, yL = 4.56;
printf("fmaxl(%.2Lf, %.2Lf) = %.2Lf\n", xL, yL, fmaxl(xL, yL));
return 0;
}

4.3 运行结果

5. fmin,fminf,fminl

5.1 函数说明

函数声明 函数功能
double fmin (double x, double y); 获取 x 和 y 中的最小值(double)
float fminf (float x, float y); 获取 x 和 y 中的最小值(float)
long double fminl (long double x, long double y); 获取 x 和 y 中的最小值(long double)

5.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>
#include<math.h>

int main()
{
double x = 10.24, y = 5.63;
printf("fmin(%.2lf, %.2lf) = %.2lf\n", x, y, fmin(x, y));

float xf = 5.63, yf = 2.89;
printf("fminf(%.2f, %.2f) = %.2f\n", xf, yf, fminf(xf, yf));

long double xL = 2.89, yL = 4.56;
printf("fminl(%.2Lf, %.2Lf) = %.2Lf\n", xL, yL, fminl(xL, yL));
return 0;
}

5.3 运行结果

6. fmod,fmodf,fmodl

6.1 函数说明

函数声明 函数功能
double fmod (double x, double y); 计算 x 除以 y 的余数(double)。
float fmodf (float x, float y); 计算 x 除以 y 的余数(float)。
long double fmodl (long double x, long double y); 计算 x 除以 y 的余数(long double)。

6.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>
#include<math.h>

int main()
{
double x = 10.24, y = 5.63;
printf("fmod(%.2lf, %.2lf) = %.20lf\n", x, y, fmod(x, y));

float xf = 5.63, yf = 2.89;
printf("fmodf(%.2f, %.2f) = %.20f\n", xf, yf, fmodf(xf, yf));

long double xL = 2.89, yL = 4.56;
printf("fmodl(%.2Lf, %.2Lf) = %.20Lf\n", xL, yL, fmodl(xL, yL));
return 0;
}

6.3 运行结果

7. fopen

7.1 函数说明

函数声明 函数功能
FILE *fopen(const char *filename, const char *mode); 使用给定的模式mode打开filename所指向的文件。

参数:

  • filename: 要打开的文件全路径名
  • mode: 文件访问模式

返回值:
如果文件顺利打开后,指向该流的文件指针就会被返回;否则文件打开失败则返回 NULL,并把错误代码存在 error 中。

文件访问模式

文件访问模式 说明
"r" 以只读模式打开文件,该文件必须存在。
"w" 以只写模式打开文件。若文件不存在则创建该文件。若文件存在则其现有内容将被清除。
"a" 以追加模式打开只写文件。若文件不存在则创建该文件;如果文件存在,则新写入的数据会被加到文件尾后。
"r+" 以读写模式打开文件,该文件必须存在。
"w+" 以读写模式打开文件。若文件不存在则创建该文件。若文件存在则其内容将被清除。
"a+" 以追加模式打开可读写文件。若文件不存在则创建该文件;如果文件存在,则新写入的数据会被加到文件尾后。
"rb" 以只读模式打开一个二进制文件。
"wb" 以只写模式打开或新建一个二进制文件。
"ab" 以追加模式打开一个二进制文件,并在文件末尾写入数据。
"rb+" 以读写模式打开一个二进制文件,该文件必须存在。
"wb+" 以读写模式打开或创建一个二进制文件。
"ab+" 以追加模式打开一个二进制文件,以便在文件末尾写入数据。该文件也是可读的。
"rt" 以只读模式打开一个文本文件。
"wt" 以只读模式打开或创建文本文件。
"at" 以追加模式打开一个文本文件,并在文件末尾写入数据。
"rt+" 以读写模式打开一个文本文件。
"wt+" 以读写模式打开或创建文本文件。
"at+" 以追加模式打开文本文件,以便在文件末尾写入数据。该文件也是可读的。

7.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string.h>
#include <stdio.h>

int main(void)
{
FILE *fp;
char buf[30] = "Hello, Huazie 123456789";
fp = fopen("STU.FIL", "w");
printf("temp.txt is created and opened\n");
fwrite(&buf, strlen(buf), 1, fp);
printf("temp.txt is writed\n");
fclose(fp);
printf("temp.txt is closed");
return 0;
}

7.3 运行结果

8. fprintf

8.1 函数说明

函数声明 函数功能
int fprintf(FILE *stream, char *format[, argument,...]); 格式化输出到一个流文件中

8.2 演示示例

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main()
{
FILE *stream;
stream = fopen("temp.txt", "w");
fprintf(stream, "%s:%d\n", "Hello Huazie", 456);
fclose(stream);
return 0;
}

8.3 运行结果

9. fputc

9.1 函数说明

函数声明 函数功能
int fputc(int ch, FILE *stream); 将字符【ch为字符的ascii码】写到文件指针stream所指向的文件的当前写指针的位置

注意: 在正常调用情况下,函数返回写入文件的字符的 ASCII 码值,出错时,返回 EOF(-1)。当正确写入一个字符或一个字节的数据后,文件内部写指针会自动后移一个字节的位置。EOF是在头文件 stdio.h中定义的宏。

9.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>

int main(void)
{
char msg[] = "Hello Huazie";
int i = 0;

while (msg[i])
{
fputc(msg[i], stdout);
i++;
}
return 0;
}

9.3 运行结果

10. fputchar

10.1 函数说明

函数声明 函数功能
int fputchar(char ch); 送一个字符到标准输出流(stdout)中,出错则返回EOF

10.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>

int main(void)
{
char msg[] = "This is a test";
int i = 0;

while (msg[i])
{
fputchar(msg[i]);
i++;
}
return 0;
}

10.3 运行结果

11. fputs

11.1 函数说明

函数声明 函数功能
int fputs(const char *str, FILE *stream); 把字符串写入到指定的流( stream) 中,但不包括空字符。

注意: fputs 函数如果成功则返回 0,如果发生错误则返回 EOF(-1)

11.2 演示示例

1
2
3
4
5
6
7
8
#include <stdio.h>

int main()
{
int result = fputs("Hello Huazie\n1234", stdout);
printf("\nresult = %d", result);
return 0;
}

11.3 运行结果

12. fread

12.1 函数说明

函数声明 函数功能
int fread(void *buffer, int size, int count, FILE *stream); 从给定输入流stream读取最多count个对象到数组buffer中

参数:

  • buffer : 指向要读取的数组中首个对象的指针
  • size : 每个对象的大小(单位是字节)
  • count : 要读取的对象个数
  • stream : 指定输入流

返回值:
返回成功读取的对象个数,若出现错误或到达文件末尾,则可能小于count。
sizecount 为零,则 fread 返回零且不进行其他动作。
fread 不区分文件尾和错误,因此调用者必须用 feofferror 才能判断发生了什么。

注意: 如果读取成功,流的文件位置指示器前进读取的字节数;否则出现错误,则流的文件位置指示器的位置不确定。同样若没有完整地读入最后一个元素,则其值也不确定。

12.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <string.h>
#include <stdio.h>

int main(void)
{
FILE *stream;
char msg[20] = "Hello, Huazie";
char buf[20];

// 以读写模式打开文件。若文件不存在则创建该文件。若文件存在则其内容将被清除。
if ((stream = fopen("temp.txt", "w+")) == NULL)
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
// 向文件流中写入数据
fwrite(msg, strlen(msg)+1, 1, stream);
// 重定位流上的文件指针到文件开头
fseek(stream, SEEK_SET, 0);
// 从文件流中读取数据
fread(buf, strlen(msg)+1, 1, stream);
printf("%s\n", buf);

fclose(stream);
return 0;
}

12.3 运行结果

13. free

13.1 函数说明

函数声明 函数功能
void free(void *ptr); 释放ptr指向的存储空间

注意: 被释放的空间通常被送入可用存储区池,以后可以在调用 mallocrealloc 以及 calloc 函数来再分配。

13.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main()
{
char *str;
str = (char *) malloc(7);
strcpy(str, "huazie");
printf("string = %-10s, Address = %u, len = %d\n", str, str, strlen(str));
str = (char *) realloc(str,25); //重新分配内存
strcat(str, ".com");
printf("string = %-10s, Address = %u, len = %d\n", str, str, strlen(str));
free(str);// 释放已分配的内存空间
//内存空间释放后,该空间上的值未知
printf("string = %-10s, Address = %u, len = %d\n", str, str, strlen(str));
return 0;
}

13.3 运行结果

14. freopen

14.1 函数说明

函数声明 函数功能
FILE * freopen(const char *filename, const char *mode, FILE *stream); 以指定模式重新指定到另一个文件

参数:

  • filename: 需要重定向到的文件名或文件路径。
  • mode: 代表文件访问权限的字符串。 参见 27 fopen
  • stream: 需要被重定向的文件流。

14.2 演示示例

1
2
3
4
5
6
7
8
9
#include<stdio.h>
int main()
{
if(freopen("temp.txt", "w", stdout) == NULL)
fprintf(stderr,"error redirecting stdout\n");
printf("Hello, %s", "Huazie");
fclose(stdout);
return 0;
}

14.3 运行结果

15. frexp,frexpf,frexpl

15.1 函数说明

函数声明 函数功能
double frexp (double x, int * exp); 将x 分解为有效位 和 2 的整数指数。(double)。
float frexpf (float x, int * exp); 将x 分解为有效位 和 2 的整数指数。(float)。
long double frexpl (long double x, int * exp); 将x 分解为有效位 和 2 的整数指数。(long double)。

注意: 有效位的绝对值范围为 0.5(包括)1(不包括)。x = 有效位 * $2^{exp}$

15.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>
#include<math.h>

int main()
{
int exp;
double x = 10.24;
printf("frexp(%.2lf, exp = %d) = %.20lf\n", x, exp, frexp(x, &exp));

float xf = 5.63;
printf("frexpf(%.2f, exp = %d) = %.20f\n", xf, exp, frexpf(xf, &exp));

long double xL = 2.89;
printf("frexpl(%.2Lf, exp = %d) = %.20Lf\n", xL, exp, frexpl(xL, &exp));
return 0;
}

15.3 运行结果

16. fscanf

16.1 函数说明

函数声明 函数功能
int fscanf(FILE *stream, char *format[,argument...]); 从一个流中执行格式化输入

注意: fscanf 遇到空格和换行时结束。它与 fgets 有区别,fgets 遇到空格不结束。

16.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int i;
printf("Input an integer: ");
if (fscanf(stdin, "%d", &i))
printf("The integer is: %d\n", i);
else
{
fprintf(stderr, "Error reading an integer from stdin.\n");
exit(1);
}
return 0;
}

16.3 运行结果

17. fseek

17.1 函数说明

函数声明 函数功能
int fseek(FILE *stream, long offset, int fromwhere); 重定位流上的文件指针位置

注意: 如果执行成功,stream 将指向以 fromwhere【偏移起始位置:文件头 **0(SEEK_SET)**,当前位置 1(SEEK_CUR),文件尾2(SEEK_END) 】为基准,偏移 offset(指针偏移量)个字节的位置。如果执行失败(比如 offset 超过文件自身大小),则不改变 stream 指向的位置。

17.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>

long filesize(FILE *stream);

int main(void)
{
FILE *stream = fopen("temp.txt", "w+");
fprintf(stream, "This is a test");
printf("The size of temp.txt is %ld bytes\n", filesize(stream));
fclose(stream);
return 0;
}

long filesize(FILE *stream)
{
long curpos, length;
// 文件指针当前位置相对于文件首的偏移字节数
curpos = ftell(stream);
// 重定向文件指针到文件尾,偏移量 0
fseek(stream, 0L, SEEK_END);
length = ftell(stream);
return length;
}

17.3 运行结果


18. fsetpos

18.1 函数说明

函数声明 函数功能
int fsetpos(FILE *stream, const fpos_t *pos); 将文件指针定位在pos指定的位置上。如果成功返回0,否则返回非0。

18.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdlib.h>
#include <stdio.h>

void showpos(FILE *stream);

int main(void)
{
FILE *stream;
fpos_t filepos;

stream = fopen("STU.FIL", "w+");
// 获取当前文件指针的位置
fgetpos(stream, &filepos);
fprintf(stream, "This is a test");
// 展示当前文件指针的位置
showpos(stream);

/* set a new file position, display it */
if (fsetpos(stream, &filepos) == 0)
showpos(stream);
else
{
fprintf(stderr, "Error setting file pointer.\n");
exit(1);
}

fclose(stream);
return 0;
}

void showpos(FILE *stream)
{
fpos_t pos;
// 展示当前文件指针的位置
fgetpos(stream, &pos);
printf("File position: %ld\n", pos);
}

18.3 运行结果

19. fstat

19.1 函数说明

函数声明 函数功能
int fstat(int handle,struct stat *buf); 由文件描述符获取文件状态

19.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <sys\stat.h>
#include <stdio.h>
#include <time.h>

int main()
{
struct stat statbuf;
FILE *stream;

if ((stream = fopen("STU.FIL", "w+")) == NULL)
{
fprintf(stderr, "Cannot open output file.\n");
exit(1);
}
fprintf(stream, "This is a test");
fflush(stream);

// get information about the file
fstat(fileno(stream), &statbuf);
fclose(stream);

if (statbuf.st_mode & S_IFCHR)
printf("Handle refers to a device.\n");
if (statbuf.st_mode & S_IFREG)
printf("Handle refers to an ordinary file.\n");
if (statbuf.st_mode & S_IREAD)
printf("User has read permission on file.\n");
if (statbuf.st_mode & S_IWRITE)
printf("User has write permission on file.\n");
// 不知道为啥,我这里文件的驱动号是空
printf("Drive letter of file: %c\n", statbuf.st_dev);
printf("Size of file in bytes: %ld\n", statbuf.st_size);
printf("Time file last opened: %s\n", ctime(&statbuf.st_ctime));
return 0;
}

19.3 运行结果

20. ftell

20.1 函数说明

函数声明 函数功能
long ftell(FILE *stream); 获取文件指针当前位置相对于文件首的偏移字节数

20.2 演示示例

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main(void)
{
FILE *stream = fopen("temp.txt", "w+");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ld\n", ftell(stream));
fclose(stream);
return 0;
}

20.3 运行结果

21. fwrite

21.1 函数说明

函数声明 函数功能
int fwrite(const void *ptr, int size, int nitems, FILE *stream); 把ptr所指向的数组中的数据写入到给定流stream中
参数:
  • ptr: 指向要被写入的元素数组的指针。
  • size: 要被写入的每个元素的大小,以字节为单位。
  • nitems: 元素的个数,每个元素的大小为 size 字节。
  • stream: 指向 FILE 对象的指针,该 FILE 对象指定了一个输出流。

注意: 如果写入成功,fwrite 返回一个 size_t 对象,表示元素的总数,该对象是一个整型数据类型。如果该数字与 nitems 参数不同,则会显示一个错误。

21.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdio.h>

struct mystruct
{
int i;
char ch;
};

int main(void)
{
FILE *stream;
struct mystruct s;
// 以只写模式打开或新建一个二进制文件。
if ((stream = fopen("test.txt", "wb")) == NULL)
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
s.i = 0;
s.ch = 'A';
fwrite(&s, sizeof(s), 1, stream);
fclose(stream);

// 以只读模式打开或新建一个二进制文件。
if ((stream = fopen("test.txt", "rb")) == NULL)
{
fprintf(stderr, "Cannot open output file.\n");
return 1;
}
struct mystruct s1;
fread(&s1, sizeof(s1), 1, stream);
printf("%d %c", s1.i, s1.ch);
fclose(stream);

return 0;
}

21.3 运行结果

参考

  1. [API Reference Document]
  2. [IO-标准C库]
  3. [fread]
  4. [freopen]
  5. [fseek]
  6. [fwrite]

C语言函数大全--f开头的函数(上)

总览

函数声明 函数功能
double fabs(double x); 返回 x 的绝对值(double)
float fabsf(float x); 返回 x 的绝对值(float)
long double fabsl(long double x); 返回 x 的绝对值(long double)
int fclose(FILE *stream); 关闭一个文件流
int fcloseall(void); 关闭除标准流(stdin、stdout、stderr、stdprn、stdaux)之外的所有打开的流,刷新所有的流缓冲区,并返回关闭的流数。
char * fcvt(double value, int ndigit, int *decpt, int *sign); 把一个双精度浮点数转换为字符串
double fdim (double x, double y); 计算 x 和 y 之间的正差值 (double)
float fdimf (float x, float y); 计算 x 和 y 之间的正差值 (float)
long double fdiml (long double x, long double y); 计算 x 和 y 之间的正差值 (long double)
FILE * fdopen(int handle, char *type); 将文件描述符和文件流相关联
int feof(FILE *stream); 检测流上的文件结束符。如果文件结束,则返回非0值,否则返回0
int ferror(FILE *stream); 检测流上的错误【返回0,表示未出错;返回非零值,表示出错。】
int fflush(FILE *stream); 清除读写缓冲区,并将缓冲区内的数据写回参数stream指向的文件中。
int fgetc(FILE *stream); 从流中读取字符
int fgetchar(void); 从流中读取字符
int fgetpos(FILE *stream); 依据当前文件的句柄,获取当前访问指针位置信息
char * fgets(char *str, int n, FILE *stream); 从指定的流中读取数据,每次读取一行
long filelength(int handle); 获取文件的长度
int fileno(FILE *stream); 获取参数stream指定的文件流所使用的文件描述符
void fillellipse(int x, int y, int xradius, int yradius); 画出并填充一椭圆
void fillpoly(int numpoints, int *polypoints); 画并填充一个多边形
int _findfirst(char *pathname, struct _finddata_t *_FindData); 搜索与指定的文件名称匹配的第一个文件,若成功则返回第一个文件的文件描述符,否则返回-1L。
int _findnext(int handle, struct _finddata_t *_FindData); 搜索与_findfirst函数提供的文件名称匹配的下一个实例,若成功则返回0,否则返回-1
int finitef (double x); 检查 x 是无穷大值还是NaN 值(double)。如果是无穷大值或NaN值,返回 0;否则返回 1。
int finitef (float x); 检查 x 是无穷大值还是NaN 值(float)。如果是无穷大值或NaN值,返回 0;否则返回 1。
void floodfill(int x, int y, int border); 填充一个有界区域

1. fabs,fabsf,fabsl

1.1 函数说明

函数声明 函数功能
double fabs(double x); 返回 x 的绝对值(double)
float fabsf(float x); 返回 x 的绝对值(float)
long double fabsl(long double x); 返回 x 的绝对值(long double)

1.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <math.h>

int main(void)
{
double result, x = -4.5;
result = fabs(x); // 取绝对值

float resultf, xf = -3.5;
resultf = fabsf(xf);

long double resultL, xL = -2.5;
resultL = fabsl(xL);

printf("The absolute value of %lf is %lf\n", x, result);

printf("The absolute value of %f is %f\n", xf, resultf);

printf("The absolute value of %Lf is %Lf\n", xL, resultL);

return 0;
}

1.3 运行结果

2. fclose

2.1 函数说明

函数声明 函数功能
int fclose(FILE *stream); 关闭一个文件流

2.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <string.h>
#include <stdio.h>

int main(void)
{
FILE *fp;
char buf[30] = "Hello, Huazie 123456789";
fp = fopen("temp.txt", "w");
printf("temp.txt is created and opened\n");
fwrite(&buf, strlen(buf), 1, fp);
printf("temp.txt is writed\n");
fclose(fp);
printf("temp.txt is closed");
return 0;
}

2.3 运行结果


3. fcloseall

3.1 函数说明

函数声明 函数功能
int fcloseall(void); 关闭除标准流(stdin、stdout、stderr、stdprn、stdaux)之外的所有打开的流,刷新所有的流缓冲区,并返回关闭的流数。

3.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>

#define fcloseall() _fcloseall();

int main()
{
int streams_closed;

fopen("temp.one", "w");
fopen("temp.two", "w");

// 关闭打开流
streams_closed = fcloseall();

if (streams_closed == EOF)
perror("Error");
else
printf("%d streams were closed.\n", streams_closed);

return 0;
}

3.3 运行结果

4. fcvt

4.1 函数说明

函数声明 函数功能
char * fcvt(double value, int ndigit, int *decpt, int *sign); 把一个双精度浮点数转换为字符串
  • value: 要转换的双精度浮点数,输入参数
  • ndigit: 取小数的位数,输入参数
  • decpt: 表示小数点的位置,输出参数
  • sign: 表示value的符号,0为正数,1为负数,输出参数

4.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main()
{
char *string;
double value;
int decpt, sign;

int ndigit = 10;
value = 9.876;
string = fcvt(value, ndigit, &decpt, &sign);
printf("string = %-18s decpt = %d sign = %d value = %lf\n", string, decpt, sign, value);

value = -123.45;
ndigit= 15;
string = fcvt(value, ndigit, &decpt, &sign);
printf("string = %-18s decpt = %d sign = %d value = %lf\n", string, decpt, sign, value);

value = 0.6789e5; /* 科学记数法 scientific notation */
ndigit = 5;
string = fcvt(value, ndigit, &decpt, &sign);
printf("string = %-18s decpt = %d sign = %d value = %lf\n", string, decpt, sign, value);

return 0;
}

4.3 运行结果

5. fdim,fdimf,fdiml

5.1 函数说明

函数声明 函数功能
double fdim (double x, double y); 计算 x 和 y 之间的正差值 (double)
float fdimf (float x, float y); 计算 x 和 y 之间的正差值 (float)
long double fdiml (long double x, long double y); 计算 x 和 y 之间的正差值 (long double)

5.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>  
#include <math.h>

int main() {

double x = 5.000011;
double y = 3.000041;

double result_d = fdim(x, y);

float xf = 5.000011f;
float yf = 3.000031f;
float result_f = fdimf(xf, yf);

long double xLD = 5.000011L;
long double yLD = 3.000021L;
long double result_ld = fdiml(xLD, yLD);

printf("fdim(%.6lf, %.6lf) = %.6lf\n", x, y, result_d);
printf("fdimf(%.6f, %.6f) = %.6f\n", xf, yf, result_f);
printf("fdiml(%.6Lf, %Lf) = %.6Lf\n", xLD, yLD, result_ld);

return 0;
}

5.3 运行结果

6. fdopen

6.1 函数说明

函数声明 函数功能
FILE * fdopen(int handle, char *type); 将文件描述符和文件流相关联

6.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <sys\stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>

int main(void)
{
int handle;
FILE *stream;
// 打开 temp.txt 文件
handle = open("temp.txt", O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
// 将文件描述符和文件流关联
stream = fdopen(handle, "w");

if (stream == NULL)
printf("fdopen failed\n");
else
{
fprintf(stream, "%s:%d\n", "Hello world", 123);
fclose(stream);
}
return 0;
}

6.3 运行结果

7. feof

7.1 函数说明

函数声明 函数功能
int feof(FILE *stream); 检测流上的文件结束符。如果文件结束,则返回非0值,否则返回0

7.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int main(void)
{
FILE *stream;
// 以读取模式,打开文件 temp.txt
stream = fopen("temp.txt", "r");

// 检查是否文件结束【0:未结束 非0:结束】
while (!feof(stream))
printf("%c", fgetc(stream));

fclose(stream);
return 0;
}

7.3 运行结果

8. ferror

8.1 函数说明

函数声明 函数功能
int ferror(FILE *stream); 检测流上的错误【返回0,表示未出错;返回非零值,表示出错。】

8.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>

int main(void)
{
FILE *stream;
// 以写模式打开文件STU.FIL
stream = fopen("STU.FIL", "w");
// 通过尝试读取来强制出现错误条件
(void) getc(stream);
// 检测流上的错误【返回0,表示未出错;返回非零值,表示出错。】
if (ferror(stream))
{
printf("Error reading from STU.FIL\n");
// 重置错误和EOF标志
clearerr(stream);
}
fclose(stream);
return 0;
}

8.3 运行结果

9. fflush

9.1 函数说明

函数声明 函数功能
int fflush(FILE *stream); 清除读写缓冲区,并将缓冲区内的数据写回参数stream指向的文件中。

9.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>

void flush(FILE *stream);

int main(void)
{
FILE *stream;
char msg[] = "This is a test";

stream = fopen("STU.FIL", "w");
fwrite(msg, strlen(msg), 1, stream);

printf("Press any key to flush STU.FIL:");
getchar();

// 将数据刷新到 STU.FIL 中而不关闭它
flush(stream);

printf("\nFile was flushed, Press any key to quit:");
getchar();
return 0;
}

void flush(FILE *stream)
{
int duphandle;

// flush the stream's internal buffer
fflush(stream);

// make a duplicate file handle
duphandle = dup(fileno(stream));

// close the duplicate handle to flush the DOS buffer
close(duphandle);
}

9.3 运行结果

10. fgetc

10.1 函数说明

函数声明 函数功能
int fgetc(FILE *stream); 从流中读取字符

10.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string.h>
#include <stdio.h>

int main(void)
{
FILE *stream;
char string[] = "This is a test";
char ch;

stream = fopen("STU.FIL", "w+");
fwrite(string, strlen(string), 1, stream);
fseek(stream, 0, SEEK_SET);

do
{
ch = fgetc(stream);
putchar(ch);
} while (ch != EOF);

fclose(stream);
return 0;
}

10.3 运行结果

11. fgetchar

11.1 函数说明

函数声明 函数功能
int fgetchar(void); 从流中读取字符

11.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main(void)
{
char ch;
printf("Enter a character followed by <Enter>: ");
// read the character from stdin
ch = fgetchar();
printf("The character read is: '%c'\n", ch);
return 0;
}

11.3 运行结果

12. fgetpos

12.1 函数说明

函数声明 函数功能
int fgetpos(FILE *stream); 依据当前文件的句柄,获取当前访问指针位置信息

12.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string.h>
#include <stdio.h>

int main(void)
{
FILE *stream;
char string[] = "This is a test";
fpos_t filepos;
stream = fopen("STU.FIL", "w+");
fwrite(string, strlen(string), 1, stream);
// report the file pointer position
fgetpos(stream, &filepos);
printf("The file pointer is at byte %lld\n", filepos);
fclose(stream);
return 0;
}

12.3 运行结果

13. fgets

13.1 函数说明

函数声明 函数功能
char * fgets(char *str, int n, FILE *stream); 从指定的流中读取数据,每次读取一行

参数:

  • str : 这是指向一个字符数组的指针,该数组存储了要读取的字符串。
  • n: 这是要读取的最大字符数(包括最后的空字符)。通常是使用以 str 传递的数组长度。
  • stream: 这是指向 FILE 对象的指针,该 FILE 对象标识了要从中读取字符的流。

注意: 如果文件中的一行,不足 n-1 个字符,则读完该行就直接结束。如若该行(包括最后一个换行符)的字符数超过 n-1,则 fgets 只返回一个不完整的行,但是,缓冲区总是以 NULL 字符结尾,对 fgets 的下一次调用会继续读该行。函数成功将返回 stream,失败或读到文件结尾返回 NULL。因此不能直接通过 fgets 的返回值来判断函数是否是出错而终止的,应该借助 feof 函数或者 ferror 函数来判断。

13.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string.h>
#include <stdio.h>

int main(void)
{
FILE *stream;
char str[] = "This is a test\n12344";
char msg[20];

stream = fopen("STU.FIL", "w+");
fwrite(str, strlen(str), 1, stream);
// seek to the start of the file
fseek(stream, 0, SEEK_SET);
while(!feof(stream))
{
fgets(msg, strlen(str) + 1, stream);
printf("%s", msg);
}
fclose(stream);
return 0;
}

13.3 运行结果

14. filelength

14.1 函数说明

函数声明 函数功能
long filelength(int handle); 获取文件的长度

14.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
#include <fcntl.h>
#include <io.h>

int main(void)
{
int handle;
char buf[30] = "This is a test\n12344";
handle = open("STU.FIL", O_CREAT);
write(handle, buf, strlen(buf));
printf("file length in bytes: %ld\n", filelength(handle));
close(handle);
return 0;
}

14.3 运行结果

15. fileno

15.1 函数说明

函数声明 函数功能
int fileno(FILE *stream); 获取参数stream指定的文件流所使用的文件描述符

15.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <fcntl.h>
#include <io.h>

int main(void)
{
FILE *stream;
char buf[30] = "This is a test\n12344";
stream = fopen("STU.FIL", "w+");
fwrite(buf, strlen(buf), 1, stream);
// 清除读写缓冲区,并将缓冲区内的数据写回参数stream指向的文件中。
fflush(stream);
// 获取参数stream指定的文件流所使用的文件描述符
int handle = fileno(stream);
printf("file length in bytes: %ld\n", filelength(handle));
fclose(stream);
return 0;
}

15.3 运行结果

16. fillellipse

16.1 函数说明

函数声明 函数功能
void fillellipse(int x, int y, int xradius, int yradius); 画出并填充一椭圆

参数

  • int x :椭圆中心点的x坐标。在二维图形环境中,x坐标通常表示水平方向上的位置,从左到右增加;
  • int y :椭圆中心点的y坐标。在二维图形环境中,y坐标通常表示垂直方向上的位置,从上到下增加;
  • int xradius :椭圆在x轴方向上的半径。它是从椭圆中心点到椭圆边缘在x轴方向上的最大距离。如果 xradius 较大,椭圆在水平方向上会显得更宽;
  • int yradius :椭圆在y轴方向上的半径。它是从椭圆中心点到椭圆边缘在y轴方向上的最大距离。如果 yradius 较大,椭圆在垂直方向上会显得更高。

16.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <graphics.h>

int main(void)
{
int gdriver = DETECT, gmode;
int xcenter, ycenter, i;

initgraph(&gdriver,&gmode,"");
xcenter = getmaxx() / 2;
ycenter = getmaxy() / 2;

for (i=EMPTY_FILL; i<USER_FILL; i++)
{
cleardevice();
// 设置填充图样和颜色
setfillstyle(i, WHITE);
fillellipse(xcenter, ycenter, 100, 50);
getch();
}

closegraph();
return 0;
}

16.3 运行结果

17. fillpoly

17.1 函数说明

函数声明 函数功能
void fillpoly(int numpoints, int *polypoints); 画并填充一个多边形

参数

  • numpoints : 多边形边数
  • polypoints : 存储各顶点坐标的数组,每两个一组表示一个顶点的X,Y坐标

17.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int i, maxx, maxy;

int poly[8];

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

maxx = getmaxx();
maxy = getmaxy();

poly[0] = 20;
poly[1] = maxy / 2;

poly[2] = maxx - 20;
poly[3] = 20;

poly[4] = maxx - 50;
poly[5] = maxy - 20;

poly[6] = maxx / 2;
poly[7] = maxy / 2;

for (i=EMPTY_FILL; i<USER_FILL; i++)
{
setfillstyle(i, getmaxcolor());
fillpoly(4, poly);
getch();
}

closegraph();
return 0;
}

17.3 运行结果

18. findfirst, findnext

18.1 函数说明

函数声明 函数功能
int _findfirst(char *pathname, struct _finddata_t *_FindData); 搜索与指定的文件名称匹配的第一个文件,若成功则返回第一个文件的文件描述符,否则返回-1L。
int _findnext(int handle, struct _finddata_t *_FindData); 搜索与_findfirst函数提供的文件名称匹配的下一个实例,若成功则返回0,否则返回-1

_findfirst 参数:

  • char *pathname :一个指向以 null 结尾的字符串的指针,该字符串指定了要搜索的文件名模式。文件名模式可以包含通配符,如 *(匹配任意数量的字符)和 ?(匹配单个字符)。例如,"*.txt" 会匹配所有以 .txt 为扩展名的文件。如果 pathname 字符串的最后一个字符是目录分隔符,那么函数将搜索该目录下的所有文件和子目录;如果 pathname 是一个空字符串,函数将搜索当前目录。
  • struct _finddata_t *_FindData :一个指向 _finddata_t 结构体的指针,该结构体用于接收关于找到的文件的信息。_finddata_t 结构体通常包含文件的属性(如是否只读、是否隐藏等)、创建时间、访问时间、修改时间、文件大小以及文件名等信息。调用 _findfirst 函数后, _FindData 指向的结构体将被填充为与文件名模式匹配的第一个文件的信息。如果搜索成功,_findfirst 函数将返回一个唯一的搜索句柄,这个句柄可以在后续的 _findnext 函数调用中使用,以查找与相同文件名模式匹配的其他文件。

_findnext 参数:

  • int handle :一个由 _findfirst 函数返回的搜索句柄。这个句柄标识了一个特定的文件搜索操作,该操作在调用 _findfirst 后开始。搜索句柄是一个唯一的标识符,用于后续调用 _findnext 来检索与原始搜索条件匹配的下一个文件或目录。
  • struct _finddata_t *_FindData :同上 _findfirst 的参数

18.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<stdio.h>
#include<io.h>

int main()
{
int handle;
struct _finddata_t FileInfo;
// 搜索与指定的文件名称匹配的第一个文件,若成功则返回第一个文件的文件描述符,否则返回-1L。
if((handle=_findfirst("E:\\Pic\\*.png", &FileInfo))==-1L)
printf("没有找到匹配的项目\n");
else
{
printf("handle=%d\n", handle);
printf("%s\n\n", FileInfo.name);
// 搜索与_findfirst函数提供的文件名称匹配的下一个实例,若成功则返回0,否则返回-1
while(_findnext(handle, &FileInfo)==0)
printf("%s\n",FileInfo.name);
_findclose(handle);
}
return 0;
}

18.3 运行结果

19. finite,finitef

19.1 函数说明

函数声明 函数功能
int finitef (double x); 检查 x 是无穷大值还是NaN 值(double)。如果是无穷大值或NaN值,返回 0;否则返回 1。
int finitef (float x); 检查 x 是无穷大值还是NaN 值(float)。如果是无穷大值或NaN值,返回 0;否则返回 1。

19.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>
#include<math.h>

int main()
{
double x = NAN, y = INFINITY, z = 10.24;
printf("finite(%.2lf) = %d\n", x, finite(x));
printf("finite(%.2lf) = %d\n", y, finite(y));
printf("finite(%.2lf) = %d\n", z, finite(z));

float xf = NAN, yf = INFINITY, zf = 5.63;
printf("\nfinitef(%.2f) = %d\n", xf, finitef(xf));
printf("finitef(%.2f) = %d\n", yf, finitef(yf));
printf("finitef(%.2f) = %d\n", zf, finitef(zf));
return 0;
}

19.3 运行结果

20. floodfill

20.1 函数说明

函数声明 函数功能
void floodfill(int x, int y, int border); 填充一个有界区域

参数

  • int x :要开始填充的区域的起始点的 x 坐标;
  • int y :要开始填充的区域的起始点的 y 坐标;
  • int border :填充的边界颜色。泛洪填充算法会从起始点 (x, y) 开始,将所有相邻的、颜色与起始点相同的区域填充为新的颜色,直到遇到边界颜色 border 为止。这样,算法就不会越过由 border 颜色定义的边界,从而保证了填充区域的准确性。

20.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

maxx = getmaxx();
maxy = getmaxy();

// select drawing color
setcolor(getmaxcolor());
// select fill color
setfillstyle(SOLID_FILL, getmaxcolor());
// draw a border around the screen
rectangle(0, 0, maxx, maxy);
// draw some circles
circle(maxx / 3, maxy /2, 50);
circle(maxx / 2, 20, 100);
circle(maxx-20, maxy-50, 75);
circle(20, maxy-20, 25);

getch();

// fill in bounded region
floodfill(2, 2, getmaxcolor());

getch();
closegraph();
return 0;
}

20.3 运行结果

参考

  1. [API Reference Document]
  2. [fgets]
  3. [_findfirst]
  4. [MATH-标准C库]

C语言函数大全--e开头的函数

总览

函数声明 函数功能
char ecvt(double value, int ndigit, int *decpt, int *sign); 把一个双精度浮点型数转换为字符串,转换结果中不包括十进制小数点
void ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius); 画一段椭圆线
int eof(int *handle); 检测文件结束
int execl(const char *pathname, const char *arg0, ... const char *argn, NULL); 载入并运行其它程序
int execlp(char *pathname, char *arg0, ... const char *argn, NULL); 载入并运行其它程序
int execlpe(const char *pathname, const char *arg0, ... const char *argn, NULL, const char *const *envp); 载入并运行其它程序
int execv(const char *pathname, char *const *argv); 载入并运行其它程序
int execve(const char *pathname, char *const argv[], char *const envp[]); 载入并运行其它程序
int execvp(const char *pathname, char *const argv[]); 载入并运行其它程序
int execvpe(const char *pathname, char *const argv[], char *const envp[]); 载入并运行其它程序
void exit(int status); 终止程序
double exp(double x); 计算 x 的基数e指数(double)
float expf(float x); 计算 x 的基数e指数(float)
long double expl(long double x); 计算 x 的基数e指数(long double)
double exp2(double x); 计算 x 的基数为2的指数(double)
float exp2f(float x); 计算 x 的基数为2的指数(float)
long double exp2l(long double x); 计算 x 的基数为2的指数(long double)
double expm1 (double x); 计算 e 的 x 次方 减 1,即 (e^x) - 1 (double)
float expm1f (float x); 计算 e 的 x 次方 减 1,即 (e^x) - 1 (float)
long double expm1l (long double x); 计算 e 的 x 次方 减 1,即 (e^x) - 1 (long double)
double erf (double x); 计算 x 的 误差函数(double)
float erff (float x); 计算 x 的 误差函数(float)
long double erfl (long double x); 计算 x 的 误差函数(long double)
double erfc (double x); 计算 x 的互补误差函数(double)
float erfcf (float x); 计算 x 的互补误差函数(float)
long double erfcl (long double x); 计算 x 的互补误差函数(long double)

1. ecvt

1.1 函数说明

函数声明 函数功能
char ecvt(double value, int ndigit, int *decpt, int *sign); 把一个双精度浮点型数转换为字符串,转换结果中不包括十进制小数点
  • value : 待转换的双精度浮点数。
  • ndigit :存储的有效数字位数。这个函数存储最多 ndigit 个数字值作为一个字符串,并添加一个结束符(‘\0’),如果 value 中的数字个数超过 ndigit,低位数字被舍入。如果少于 ndigit 个数字,该字符串用 0填充。
  • decpt :指出给出小数点位置的整数值, 它是从该字符串的开头位置计算的。0 或负数指出小数点在第一个数字的左边。
  • sign :指出一个指出转换的数的符号的整数。如果该整数为 0,这个数为正数,否则为负数。

1.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main()
{
char *string;
double value;
int decpt, sign;

int ndigit = 10;
value = 9.876;
string = ecvt(value, ndigit, &decpt, &sign);
printf("string = %-16s decpt = %d sign = %d value = %lf\n", string, decpt, sign, value);

value = -123.45;
ndigit= 15;
string = ecvt(value, ndigit, &decpt, &sign);
printf("string = %-16s decpt = %d sign = %d value = %lf\n", string, decpt, sign, value);

value = 0.6789e5; /* 科学记数法 scientific notation */
ndigit = 5;
string = ecvt(value, ndigit, &decpt, &sign);
printf("string = %-16s decpt = %d sign = %d value = %lf\n", string, decpt, sign, value);

return 0;
}

1.3 运行结果

2. ellipse

2.1 函数说明

函数声明 函数功能
void ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius); 画一段椭圆线

(x, y) 为中心,xradiusyradiusx 轴y 轴 半径,从角 stangle 开始,endangle 结束,画一段椭圆线。当stangle=0,endangle=360 时,画出一个完整的椭圆

2.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
// request auto detection
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
int stangle = 0, endangle = 360, midangle = 180;
int xradius = 100, yradius = 50;

// initialize graphics, local variables
initgraph(&gdriver, &gmode, "");

// read result of initialization
errorcode = graphresult();
if (errorcode != grOk) // an error occurred
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());

// draw ellipse
ellipse(midx, 50, midangle, endangle, xradius, yradius);

ellipse(midx, midy, stangle, endangle, xradius, yradius);

ellipse(midx, getmaxy() - 50, stangle, midangle, xradius, yradius);

getch();
closegraph();
return 0;
}

2.3 运行结果

3. eof

3.1 函数说明

函数声明 函数功能
int eof(int *handle); 检测文件结束

3.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <sys\stat.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>

int main(void)
{
int handle;
char msg[] = "This is a test";
char ch;

// create a file
handle = open("STU.FIL", O_CREAT | O_RDWR, S_IREAD | S_IWRITE);

// write some data to the file
write(handle, msg, strlen(msg));

// seek to the beginning of the file
lseek(handle, 0L, SEEK_SET);

// reads chars from the file until hit EOF
do
{
read(handle, &ch, 1);
printf("%c", ch);
} while (!eof(handle));

close(handle);
return 0;
}

3.3 运行结果

4. execl

4.1 函数说明

函数声明 函数功能
int execl(const char *pathname, const char *arg0, ... const char *argn, NULL); 载入并运行其它程序

注意: execl 函数,其后缀 l 代表 list,也就是参数列表的意思。第一个参数 path 字符指针指向要执行的文件路径, 接下来的参数代表执行该文件时传递的参数列表:argv[0],argv[1]... ,最后一个参数须用空指针 NULL 作结束。

4.2 演示示例

4.2.1 SubTest.c

1
2
3
4
5
6
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("exec %s, Hello, %s", argv[0], argv[1]);
return 0;
}

4.2.2 Test.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <process.h>
#include <stdio.h>
#include <errno.h>

void main(int argc, char *argv[])
{
int i;
printf("Command line arguments:\n");
for (i=0; i<argc; i++)
printf("[%d] : %s\n", i, argv[i]);
printf("exec SubTest with subargv ...\n");
// 成功则不返回值, 失败返回-1, 失败原因存于errno中,可通过perror()打印
// 第一个参数需要执行文件的全路径,这里写直接文件名,是因为和当前源码在同一目录中
int result = execl("SubTest.exe", argv[0], "Huazie" , NULL);
// 执行成功,这里不会执行到
printf("result = %d\n", result);
perror("exec error");
exit(1);
}

4.3 运行结果

执行失败:

执行成功:

5. execle

5.1 函数说明

函数声明 函数功能
int execle(const char *pathname, const char *arg0, ... const char *argn, NULL, const char *const *envp); 载入并运行其它程序

注意: execl 函数是用来执行参数 path 字符串所代表的文件路径。接下来的参数代表执行该文件时传递过去的 argv[0], argv[1]…,并且倒数第二个参数必须用空指针 NULL 作结束,最后一个参数为 环境变量

5.2 演示示例

5.2.1 SubEnvTest.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <process.h>
#include <processenv.h>
#include <stdio.h>

int main(int argc, char *argv[], char **envp)
{
printf("SubEnvTest Command line arguments:\n");
for (int i=0; i<argc; i++)
printf("[%d] : %s\n", i, argv[i]);
printf("exec %s, Hello, %s\n", argv[0], argv[1]);

for (int i = 0; envp[i] != NULL; i++)
{
printf("%s\n", envp[i]);
}
// while(*envp != NULL)
// printf(" %s\n", *(envp++));

return 0;
}

5.2.2 Test.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <process.h>
#include <stdio.h>
#include <errno.h>

void main(int argc, char *argv[])
{
int i;
printf("Command line arguments:\n");
for (i=0; i<argc; i++)
printf("[%d] : %s\n", i, argv[i]);
printf("exec SubEnvTest with subargv ...\n");
const char *envp[] = {"AUTHOR=Huazie", "DATE=2023-03-28", NULL}; // 环境变量

// 成功则不返回值, 失败返回-1, 失败原因存于errno中,可通过perror()打印
// 第一个参数需要执行文件的全路径,这里直接写文件名,是因为和当前源码在同一目录中
int result = execle("SubEnvTest.exe", argv[0], "Huazie" , NULL, envp);
// 执行成功,这里不会执行到
printf("result = %d\n", result);
perror("exec error");
exit(1);
}

5.3 运行结果

6. execlp

6.1 函数说明

函数声明 函数功能
int execlp(char *pathname, char *arg0, ... const char *argn, NULL); 载入并运行其它程序

注意: execlp 函数会从 PATH 环境变量所指的目录中查找符合参数 pathname 的文件名,找到后便执行该文件,然后将第二个以后的参数当做该文件的arg0, arg1, …,最后一个参数必须用 空指针 NULL 作结束。

6.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <process.h>
#include <stdio.h>
#include <errno.h>

void main(int argc, char *argv[])
{
int i;
printf("Command line arguments:\n");
for (i=0; i<argc; i++)
printf("[%d] : %s\n", i, argv[i]);
printf("exec java with subargv ...\n");
// 成功则不返回值, 失败返回-1, 失败原因存于errno中,可通过perror()打印
int result = execlp("java.exe", "java", "-version", NULL);
// 执行成功,这里不会执行到
printf("result = %d\n", result);
perror("exec error");
exit(1);
}

6.3 运行结果

7. execlpe

7.1 函数说明

函数声明 函数功能
int execlpe(const char *pathname, const char *arg0, ... const char *argn, NULL, const char *const *envp); 载入并运行其它程序

注意: execlp 函数会从 PATH 环境变量所指的目录中查找符合参数 pathname 的文件名,找到后便执行该文件,然后将第二个以后的参数当做该文件的arg0, arg1, …,其中倒数第二个参数必须用 空指针 NULL 作结束,最后一个参数为 环境变量

7.2 演示示例

7.2.1 SubEnvTest.c

参考 5.2.1SubEnvTest.c

7.2.2 Test.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <process.h>
#include <stdio.h>
#include <errno.h>

void main(int argc, char *argv[])
{
int i;
printf("Command line arguments:\n");
for (i=0; i<argc; i++)
printf("[%d] : %s\n", i, argv[i]);
printf("exec SubEnvTest with subargv ...\n");
const char *envp[] = {"AUTHOR=Huazie", "DATE=2023-03-28", NULL}; // 环境变量
// 成功则不返回值, 失败返回-1, 失败原因存于errno中,可通过perror()打印
int result = execlpe("SubEnvTest", argv[0], "Huazie", NULL, envp);
// 执行成功,这里不会执行到
printf("result = %d\n", result);
perror("exec error");
exit(1);
}

7.3 运行结果

8. execv

8.1 函数说明

函数声明 函数功能
int execv(const char *pathname, char *const *argv); 载入并运行其它程序

注意:execv 函数用来运行參数 pathname 字符串所指向的程序,第二个参数 argv 为參数列表【该数组的最后一个元素必须是空指针 NULL】。

8.2 演示示例

8.2.1 SubTest.c

参考 4.2.1SubTest.c

8.2.2 Test.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <process.h>
#include <stdio.h>
#include <errno.h>

void main(int argc, char *argv[])
{
int i;
printf("Command line arguments:\n");
for (i=0; i<argc; i++)
printf("[%d] : %s\n", i, argv[i]);
printf("exec SubTest with subargv ...\n");
char *const subargv[] = {argv[0], "Huazie" , NULL}; // 参数列表
// 成功则不返回值, 失败返回-1, 失败原因存于errno中,可通过perror()打印
// 第一个参数需要执行文件的全路径,这里写直接文件名,是因为和当前源码在同一目录中
int result = execv("SubTest.exe", subargv);
// 执行成功,这里不会执行到
printf("result = %d\n", result);
perror("exec error");
exit(1);
}

8.3 运行结果

9. execve

9.1 函数说明

函数声明 函数功能
int execve(const char *pathname, char *const argv[], char *const envp[]); 载入并运行其它程序

注意:execve 函数用来运行參数 pathname 字符串所指向的程序,第二个参数 argv 为參数列表【该数组的最后一个元素必须是空指针 NULL】,最后一个参数为 环境变量

9.2 演示示例

9.2.1 SubEnvTest.c

参考 5.2.1SubEnvTest.c

9.2.2 Test.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <process.h>
#include <stdio.h>
#include <errno.h>

void main(int argc, char *argv[])
{
int i;
printf("Command line arguments:\n");
for (i=0; i<argc; i++)
printf("[%d] : %s\n", i, argv[i]);
printf("exec SubEnvTest with subargv ...\n");
char *const subargv[] = {argv[0], "Huazie" , NULL}; // 参数列表
char *const envp[] = {"AUTHOR=Huazie", "DATE=2023-03-28", NULL}; // 环境变量
// 成功则不返回值, 失败返回-1, 失败原因存于errno中,可通过perror()打印
// 第一个参数需要执行文件的全路径,这里写直接文件名,是因为和当前源码在同一目录中
int result = execve("SubEnvTest.exe", subargv, envp);
// 执行成功,这里不会执行到
printf("result = %d\n", result);
perror("exec error");
exit(1);
}

9.3 运行结果

10. execvp

10.1 函数说明

函数声明 函数功能
int execvp(const char *pathname, char *const argv[]); 载入并运行其它程序

注意:execvp 函会从 PATH 环境变量所指的目录中查找符合参数 pathname 的文件名,找到后便执行该文件,第二个参数 argv 为參数列表【该数组的最后一个元素必须是空指针 NULL】。

10.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <process.h>
#include <stdio.h>
#include <errno.h>

void main(int argc, char *argv[])
{
int i;
printf("Command line arguments:\n");
for (i=0; i<argc; i++)
printf("[%d] : %s\n", i, argv[i]);
printf("exec java with subargv ...\n");
char *const subargv[] = {"java", "-version" , NULL}; // 参数列表
// 成功则不返回值, 失败返回-1, 失败原因存于errno中,可通过perror()打印
int result = execvp("java.exe", subargv);
// 执行成功,这里不会执行到
printf("result = %d\n", result);
perror("exec error");
exit(1);
}

10.3 运行结果

11. execvpe

11.1 函数说明

函数声明 函数功能
int execvpe(const char *pathname, char *const argv[], char *const envp[]); 载入并运行其它程序

注意:execvpe 函会从 PATH 环境变量所指的目录中查找符合参数 pathname 的文件名,找到后便执行该文件,第二个参数 argv 为參数列表【该数组的最后一个元素必须是空指针 NULL】,最后一个参数为 环境变量

11.2 演示示例

11.2.1 SubEnvTest.c

参考 5.2.1SubEnvTest.c

11.2.2 Test.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <process.h>
#include <stdio.h>
#include <errno.h>

void main(int argc, char *argv[])
{
int i;
printf("Command line arguments:\n");
for (i=0; i<argc; i++)
printf("[%d] : %s\n", i, argv[i]);
printf("exec SubEnvTest with subargv ...\n");
char *const subargv[] = {argv[0], "Huazie" , NULL}; // 参数列表
char *const envp[] = {"AUTHOR=Huazie", "DATE=2023-03-28", NULL}; // 环境变量
// 成功则不返回值, 失败返回-1, 失败原因存于errno中,可通过perror()打印
int result = execvpe("SubEnvTest.exe", subargv, envp);
// 执行成功,这里不会执行到
printf("result = %d\n", result);
perror("exec error");
exit(1);
}

11.3 运行结果

12. exit

12.1 函数说明

函数声明 函数功能
void exit(int status); 终止程序

注意: exit 函数通常是用来终结程序用的,使用后程序自动结束,跳回操作系统。exit(0) 表示程序正常退出【相当于主函数 return 0;】,exit⑴ 表示程序异常退出【相当于主函数 return 1;】。

12.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int status;

printf("Enter either 1 or 2\n");
status = getchar();
/* Sets DOS errorlevel */
exit(status - '0');

/* Note: this line is never reached */
printf("this line is never reached!");
return 0;
}

12.3 运行结果

13. exp,expf,expl

13.1 函数说明

函数声明 函数功能
double exp(double x); 计算 x 的基数e指数(double)
float expf(float x); 计算 x 的基数e指数(float)
long double expl(long double x); 计算 x 的基数e指数(long double)

13.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <math.h>

int main(void)
{
double result, x = 4.0;
result = exp(x);

float resultf, xf = 4.0;
resultf = expf(xf);

long double resultL, xL = 4.0;
resultL = expl(xL);

printf("\n'e' raised to the power of %lf (e ^ %lf) = %.20lf\n", x, x, result);
printf("\n'e' raised to the power of %f (e ^ %f) = %.20f\n", xf, xf, resultf);
printf("\n'e' raised to the power of %Lf (e ^ %Lf) = %.20Lf\n", xL, xL, resultL);

return 0;
}

13.3 运行结果

14. exp2,exp2f,exp2l

14.1 函数说明

函数声明 函数功能
double exp2(double x); 计算 x 的基数为2的指数(double)
float exp2f(float x); 计算 x 的基数为2的指数(float)
long double exp2l(long double x); 计算 x 的基数为2的指数(long double)

14.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <math.h>

int main(void)
{
double result, x = 4.5;
result = exp2(x);

float resultf, xf = 4.5;
resultf = exp2f(xf);

long double resultL, xL = 4.5;
resultL = exp2l(xL);

printf("\n'2' raised to the power of %lf (2 ^ %lf) = %.20lf\n", x, x, result);
printf("\n'2' raised to the power of %f (2 ^ %f) = %.20f\n", xf, xf, resultf);
printf("\n'2' raised to the power of %Lf (2 ^ %Lf) = %.20Lf\n", xL, xL, resultL);

return 0;
}

14.3 运行结果

15. expm1,expm1f,expm1l

15.1 函数说明

函数声明 函数功能
double expm1 (double x); 计算 e 的 x 次方 减 1,即 (e^x) - 1 (double)
float expm1f (float x); 计算 e 的 x 次方 减 1,即 (e^x) - 1 (float)
long double expm1l (long double x); 计算 e 的 x 次方 减 1,即 (e^x) - 1 (long double)

15.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <math.h>

int main(void)
{
double result, result1, x = 4.0;
result = exp(x);
result1 = expm1(x);

float resultf, resultf1, xf = 4.0;
resultf = expf(xf);
resultf1 = expm1f(xf);

long double resultL, resultL1, xL = 4.0;
resultL = expl(xL);
resultL1 = expm1l(xL);

printf("\n'e' raised to the power of %lf (e ^ %lf) = %.20lf\n", x, x, result);
printf("\n'e' raised to the power of %lf minus one (e ^ %lf - 1) = %.20lf\n", x, x, result1);

printf("\n'e' raised to the power of %f (e ^ %f) = %.20f\n", xf, xf, resultf);
printf("\n'e' raised to the power of %f minus one (e ^ %f - 1) = %.20f\n", xf, xf, resultf1);

printf("\n'e' raised to the power of %Lf (e ^ %Lf) = %.20Lf\n", xL, xL, resultL);
printf("\n'e' raised to the power of %Lf minus one (e ^ %Lf - 1) = %.20Lf\n", xL, xL, resultL1);

return 0;
}

15.3 运行结果

16. erf,erff,erfl

16.1 函数说明

函数声明 函数功能
double erf (double x); 计算 x 的 误差函数(double)
float erff (float x); 计算 x 的 误差函数(float)
long double erfl (long double x); 计算 x 的 误差函数(long double)

16.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <math.h>

int main(void)
{
double result, x = 2.0;
result = erf(x); // 高斯误差函数

float resultf, xf = 2.0;
resultf = erff(xf);

long double resultL, xL = 2.0;
resultL = erfl(xL);

printf("the error function of %lf = %.20lf\n", x, result);
printf("the error function of %f = %.20f\n", xf, resultf);
printf("the error function of %Lf = %.20Lf\n", xL, resultL);

return 0;
}

16.3 运行结果

17. erfc,erfcf,erfcl

17.1 函数说明

函数声明 函数功能
double erfc (double x); 计算 x 的互补误差函数(double)
float erfcf (float x); 计算 x 的互补误差函数(float)
long double erfcl (long double x); 计算 x 的互补误差函数(long double)

17.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <math.h>

int main(void)
{
double result, x = 2.0;
result = erfc(x); // 互补误差函数

float resultf, xf = 2.0;
resultf = erfcf(xf);

long double resultL, xL = 2.0;
resultL = erfcl(xL);

printf("the complementary error function of %lf = %.20lf\n", x, result);
printf("the complementary error function of %f = %.20f\n", xf, resultf);
printf("the complementary error function of %Lf = %.20Lf\n", xL, resultL);

return 0;
}

17.3 运行结果

参考

  1. [API Reference Document]
  2. [ecvt 函数]
  3. [exec函数]

C语言函数大全--d开头的函数

总览

函数声明 函数功能
void detectgraph(int *graphdriver, int *graphmode); 通过检测硬件确定图形驱动程序和模式
double difftime(time_t time2, time_t time1); 计算两个时刻之间的时间差
void disable(void); 屏蔽中断
div_t div(int number, int denom); 将两个整数相除, 返回商和余数
void drawpoly(int numpoints, int *polypoints); 画多边形
int dup(int handle); 复制文件描述符;若成功为新的文件描述,若出错为-1
int dup2(int oldhandle, int newhandle); 复制文件描述符;若成功为新的文件描述,若出错为-1。

1. detectgraph

1.1 函数说明

函数声明 函数功能
void detectgraph(int *graphdriver, int *graphmode); 通过检测硬件确定图形驱动程序和模式

1.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

/* names of the various cards supported */
char *dname[] = {
"requests detection",
"a CGA",
"an MCGA",
"an EGA",
"a 64K EGA",
"a monochrome EGA",
"an IBM 8514",
"a Hercules monochrome",
"an AT&T 6300 PC",
"a VGA",
"an IBM 3270 PC"
};

int main(void)
{
int gdriver, gmode, errorcode;

detectgraph(&gdriver, &gmode);

initgraph(&gdriver, &gmode, "");

errorcode = graphresult();

if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

printf("You have [%s] video display card.\n", dname[gdriver]);
printf("Press any key to halt:");
getch();
return 0;
}

1.3 运行结果

2. difftime

2.1 函数说明

函数声明 函数功能
double difftime(time_t time2, time_t time1); 计算两个时刻之间的时间差

2.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <time.h>

int main(void)
{
time_t first, second; // time_t 相当于 long
first = time(NULL); // Gets system time
getchar();
second = time(NULL); // Gets system time again
printf("The difference is: %lf seconds\n", difftime(second, first));
return 0;
}

在上述的示例代码中,

  • 首先,我们定义了两个 time_t 类型的变量 firstsecond
  • 然后,调用 time(NULL) 函数获取当前的系统时间,并赋值给 first
  • 接着,调用 getchar() 函数等待用户输入,模拟延时的功能;
  • 再然后,继续调用 time(NULL) 函数获取当前的系统时间,并赋值给 second
  • 再接着,调用 difftime() 函数计算 firstsecond 之间的时间差【单位:秒】
  • 最终,输出时间差,并结束程序。

2.3 运行结果

3. disable

3.1 函数说明

函数声明 函数功能
void disable(void); 屏蔽中断

3.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 中断服务示例
#include <stdio.h>
#include <dos.h>
#include <conio.h>
// 定义一个宏INTR,代表时钟中断的十六进制向量值
#define INTR 0X1C
// 声明一个函数指针oldhandler,该指针指向一个没有参数且返回void的函数。
// 这种函数通常用于中断处理程序
void interrupt (*oldhandler)(void);

int count=0;

void interrupt handler(void)
{
// 禁用其他中断,确保此中断处理程序执行完毕前不再响应其他中断
disable();
count++;
// 启用其他中断
enable();
// 调用原先的中断处理程序
(*oldhandler)();
}

int main(void)
{
// 获取时钟中断的原始处理程序,并将其存储在oldhandler指向的函数中
oldhandler = getvect(INTR);
// 将时钟中断的处理程序设置为handler函数
setvect(INTR, handler);

while (count < 20)
printf("count is %d\n",count);
// 恢复时钟中断的原始处理程序
setvect(INTR, oldhandler);

return 0;
}

注意: 这个程序可能无法在现代操作系统上直接运行,因为其中的一些函数(如disable()enable()getvect()setvect())是特定于 DOS 的。如果你想在现代操作系统(如 LinuxWindows)上运行这个程序,你可能需要使用更现代的方法来处理中断或使用 DOS 模拟器。

4. div

4.1 函数说明

函数声明 函数功能
div_t div(int number, int denom); 将两个整数相除, 返回商和余数

4.2 演示示例

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
#include <math.h>

int main(void)
{
div_t x = div(10,3);
// 商 和 余数
printf("10 div 3 = %d remainder %d\n", x.quot, x.rem);
return 0;
}

4.3 运行结果

5. drawpoly

5.1 函数说明

函数声明 函数功能
void drawpoly(int numpoints, int *polypoints); 画多边形

参数说明:

  • numpoints:多边形顶点的数量

  • polypoints:一个整数数组,包含多边形的各个顶点的坐标。

5.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <graphics.h>
#include <stdio.h>

int main(void)
{
// request auto detection
int gdriver = DETECT, gmode, errorcode;
int maxx, maxy;

// our polygon array
int poly[10];

// initialize graphics and local variables
initgraph(&gdriver, &gmode, "");

// read result of initialization
errorcode = graphresult();
if (errorcode != grOk) // an error occurred
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
// terminate with an error code
exit(1);
}

maxx = getmaxx();
maxy = getmaxy();

poly[0] = 20;
poly[1] = maxy / 2;

poly[2] = maxx - 20;
poly[3] = 20;

poly[4] = maxx - 50;
poly[5] = maxy - 20;

poly[6] = maxx / 2;
poly[7] = maxy / 2;

// drawpoly doesn't automatically close the polygon, so we close it.

poly[8] = poly[0];
poly[9] = poly[1];

// draw the polygon
drawpoly(5, poly);

// clean up
getch();
closegraph();
return 0;
}

5.3 运行结果

6. dup

6.1 函数说明

函数声明 函数功能
int dup(int handle); 复制文件描述符;若成功为新的文件描述,若出错为-1

dup 返回的新文件描述符一定是当前可用文件描述中的最小数值。

6.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <fcntl.h>
#include <io.h>

void flush(FILE *stream);

int main(void)
{
FILE *fp;
char msg[] = "This is a test";

fp = fopen("STU.FIL", "w");

fwrite(msg, strlen(msg), 1, fp);

int handle;

handle = open("temp.txt", _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE);
printf("file hanlde : %d\n", handle);

printf("Press any key to flush STU.FIL:");
getchar();

flush(fp);

printf("\nFile was flushed, Press any key to quit:");
getchar();
return 0;
}

void flush(FILE *stream)
{
int duphandle;

fflush(stream);

duphandle = dup(fileno(stream));

printf("duplicate file hanlde : %d", duphandle);

close(duphandle);
}

上述代码可以简单总结如下:

  1. 首先,它打开一个名为"STU.FIL"的文件,并以写入模式打开。
  2. 然后,将字符串"This is a test"写入该文件。
  3. 接下来,它打开一个名为 "temp.txt" 的文件,并获取其文件句柄。
  4. 然后,提示用户按下任意键以刷新 "STU.FIL" 文件。
  5. 接着,调用自定义的flush函数来刷新文件缓冲区。
    • 首先调用fflush函数来刷新传入的文件流的缓冲区;
    • 然后,使用dup函数复制文件描述符,并将其存储在duphandle变量中;
    • 接着,打印出复制的文件句柄;
    • 最后,关闭复制的文件句柄。
  6. 最后,再次提示用户按下任意键以退出程序。

6.3 运行结果

7. dup2

7.1 函数说明

函数声明 函数功能
int dup2(int oldhandle, int newhandle); 复制文件描述符;若成功为新的文件描述,若出错为-1。

dup2 可以用 newhandle 参数指定新的描述符数值。如果 newhandle 已经打开,则先关闭。若 oldhandle = newhandle,则 dup2 返回 newhandle,而不关闭它。

7.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <sys\stat.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>

int main(void)
{
#define STDOUT 1

int handle, oldstdout;
char msg[] = "This is a test1";

handle = open("STU.FIL", O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
printf("open file handle : %d\n", handle);

oldstdout = dup(STDOUT);
printf("dup file handle : %d", oldstdout);

dup2(handle, STDOUT);

close(handle);

write(STDOUT, msg, strlen(msg));

dup2(oldstdout, STDOUT);

close(oldstdout);

return 0;
}

上述代码简单分析如下:

  • 定义常量 STDOUT,其值为 1,表示标准输出的文件描述符;
  • 定义整型变量 handleoldstdout,以及字符数组 msg,用于存储要写入文件的字符串;
  • 使用 open 函数打开名为 "STU.FIL" 的文件,以创建和读写模式(O_CREAT | O_RDWR)打开,并设置文件权限为可读可写(S_IREAD | S_IWRITE);将返回的文件描述符赋值给 handle,并打印出来;
  • 使用 dup 函数备份当前的标准输出(STDOUT),将备份的文件描述符赋值给 oldstdout,并打印出来;
  • 使用 dup2 函数将标准输出重定向到 handle 指向的文件,即将后续的输出内容写入到 "STU.FIL" 文件中;
  • 关闭 handle 指向的文件句柄;
  • 使用 write 函数将 msg 字符串写入到标准输出(此时已经重定向到文件),长度为字符串的长度;
  • 使用 dup2 函数将标准输出恢复到备份的文件描述符 oldstdout,即将后续的输出内容输出到屏幕上。
  • 关闭 oldstdout 指向的文件句柄。

7.3 运行结果

参考

  1. [API Reference Document]

C语言函数大全--c开头的函数

总览

函数声明 函数功能
double cbrt (double x) 计算 x 的立方根(double)
float cbrtf (float x) 计算 x 的立方根(float)
long double cbrtl (long double x) 计算 x 的立方根(long double)
double ceil (double x) 计算大于或等于x的最小整数(double)
float ceilf (float x) 计算大于或等于x的最小整数(float)
long double ceill (long double x) 计算大于或等于x的最小整数(long double)
double copysign (double x, double y); 通过组合x的大小和y的符号生成一个值。(double) 例如,如果x为2.0,y为-1.0,则将生成值-2.0。
float copysignf (float x, float y); 通过组合x的大小和y的符号生成一个值。(float) 例如,如果x为2.0,y为-1.0,则将生成值-2.0。
long double copysignl (long double x, long double y); 通过组合x的大小和y的符号生成一个值。(long double) 例如,如果x为2.0,y为-1.0,则将生成值-2.0。
int chdir(const char *path); 更改当前的工作目录。如果成功返回 0,否则返回 -1
int chmod( const char *filename, int pmode); 变更文件或目录的权限。如果改变成功返回0,否则返回-1
int chsize(int handle, long size); 改变文件大小
void circle(int x, int y, int radius); 在给定半径radius,以(x, y)为圆心画圆
void cleardevice(void); 清除图形屏幕
void clearerr(FILE *stream); 复位错误标志,使用它可以使文件错误标志和文件结束标志置为 0。
void clearviewport(); 清除图形视区
int close(int handle); 通过文件描述符handle,来关闭文件,成功返回0,出错返回-1
long clock(void); 确定处理器调用某个进程或函数所用的时间
void closegraph(); 关闭图形系统
double cos(double x); 计算x的余弦(double)
float cosf(float x); 计算x的余弦(float)
long double cosl(long double x); 计算x的余弦(long double)
double cosh(double x); 计算x的双曲余弦(double)
float coshf(float x); 计算x的双曲余弦(float)
long double coshl(long double x); 计算x的双曲余弦(long double)
int creat (const char *filename, int mode); 创建一个新文件或重写一个已存在的文件
char *ctime(const time_t *time); 把日期和时间转换为字符串

1. cbrt,cbrtf,cbrtl

1.1 函数说明

函数声明 函数功能
double cbrt (double x) 计算 x 的立方根(double)
float cbrtf (float x) 计算 x 的立方根(float)
long double cbrtl (long double x) 计算 x 的立方根(long double)

1.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <math.h>

int main(void)
{
double x = 8.0;
float xf = 27.0;
long double xL = 64.0;

// 立方根
printf("The cube root of the double value %.4lf is %.4lf\n", x, cbrt(x));
printf("The cube root of the float value %.4f is %.4f\n", xf, cbrtf(xf));
printf("The cube root of the long double value %.4Lf is %.4Lf", xL, cbrtl(xL));

return 0;
}

1.3 运行结果

2. ceil,ceilf,ceill

2.1 函数说明

函数声明 函数功能
double ceil (double x) 计算大于或等于x的最小整数(double)
float ceilf (float x) 计算大于或等于x的最小整数(float)
long double ceill (long double x) 计算大于或等于x的最小整数(long double)

2.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <math.h>

int main(void)
{
double x = 2.3;
float xf = 2.5;
long double xL = 2.8;

// 计算大于或等于x的最小整数
printf("The minimum integer greater than or equal to the [x = %.4lf] is %.4lf\n", x, ceil(x));
printf("The minimum integer greater than or equal to the [x = %.4f] is %.4f\n", xf, ceilf(xf));
printf("The minimum integer greater than or equal to the [x = %.4Lf] is %.4Lf", xL, ceill(xL));
return 0;
}

2.3 运行结果

3. copysign,copysignf,copysignl

3.1 函数说明

函数声明 函数功能
double copysign (double x, double y); 通过组合x的大小和y的符号生成一个值。(double) 例如,如果x为2.0,y为-1.0,则将生成值-2.0。
float copysignf (float x, float y); 通过组合x的大小和y的符号生成一个值。(float) 例如,如果x为2.0,y为-1.0,则将生成值-2.0。
long double copysignl (long double x, long double y); 通过组合x的大小和y的符号生成一个值。(long double) 例如,如果x为2.0,y为-1.0,则将生成值-2.0。

3.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <math.h>

int main(void)
{
double x = 2.0, y = -1.0;
float xf = 2.0, yf = -1.0;
long double xL = 2.0, yL = -1.0;

// 通过组合x的大小和y的符号生成一个值
printf("The double value by combining the magnitude of [x = %.4lf] and the sign of [y = %.4lf] is %.4lf\n", x, y, copysign(x, y));
printf("The float value by combining the magnitude of [x = %.4f] and the sign of [y = %.4f] is %.4f\n", xf, yf, copysignf(xf, yf));
printf("The long double value by combining the magnitude of [x = %.4Lf] and the sign of [y = %.4Lf] is %.4Lf", xL, yL, copysignl(xL, yL));
return 0;
}

3.3 运行结果

4. chdir

4.1 函数说明

函数声明 函数功能
int chdir(const char *path); 更改当前的工作目录。如果成功返回 0,否则返回 -1

4.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <stdlib.h>
#include <dir.h>

#define MAXDIR 1000
char old_dir[MAXDIR];
char new_dir[MAXDIR];

int main()
{
if (!getcwd(old_dir, MAXDIR)) // 获取当前的目录
{
perror("getcwd()");
exit(1);
}
printf("Current directory is: %s\n", old_dir);

if (chdir("D:\\")) // 切换目录,成功返回0,失败返回-1
{
perror("chdir()");
exit(1);
}

if (!getcwd(new_dir, MAXDIR))
{
perror("getcwd()");
exit(1);
}
printf("Current directory is now: %s\n", new_dir);

printf("\nChanging back to orignal directory: %s\n", old_dir);

if (chdir(old_dir))
{
perror("chdir()");
exit(1);
}

return 0;
}

4.3 运行结果

5. chmod

5.1 函数说明

函数声明 函数功能
int chmod( const char *filename, int pmode); 变更文件或目录的权限。如果改变成功返回0,否则返回-1

参数:

  • const char *filename : 表示要更改权限的文件或目录的路径。路径可以是相对路径或绝对路径。
  • int pmode :表示要设置的新权限。权限通常使用八进制数表示,每个八进制数字代表一个组(所有者、组、其他用户)的读、写和执行权限。

可以使用以下宏来组合权限:

  • S_ISUID: 设置用户ID位
  • S_ISGID: 设置组ID位
  • S_ISVTX: 粘滞位
  • S_IREAD: 读权限 (4)
  • S_IWRITE: 写权限 (2)
  • S_IEXEC: 执行权限 (1)

这些宏可以按位或操作符 (|) 组合使用。例如:

  • 要设置 读 写 权限,可以使用 S_IREAD | S_IWRITE
  • 要设置 读 写 执行 权限,可以使用 S_IREAD | S_IWRITE | S_IEXEC

5.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <sys\stat.h>
#include <stdio.h>
#include <io.h>

void make_read_only(char *filename);

int main(void)
{
make_read_only("NOTEXIST.FIL");
make_read_only("students.txt");
return 0;
}

void make_read_only(char *filename)
{
int stat;

stat = chmod(filename, S_IREAD);
if (stat)
printf("Couldn't make %s read-only\n", filename);
else
printf("Made %s read-only\n", filename);
}

5.3 运行结果

6. chsize

6.1 函数说明

函数声明 函数功能
int chsize(int handle, long size); 改变文件大小

参数:

  • handle : 文件句柄,表示要改变大小的文件。这个句柄通常是通过调用 open 或 creat 函数获得的。
  • size : 新的文件大小,以字节为单位。如果新的大小比当前文件大小大,则文件会被扩展,新增的部分会用零填充。如果新的大小比当前文件大小小,则文件会被截断,多余的部分会被丢弃。

6.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
int main()
{
int fh, result;
unsigned int nbytes = 2048;
// 打开文件
if((fh=open("temp.txt", _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE)) != -1)
{
printf("File length before: %ld\n", filelength(fh)); // 获取文件大小
if((result=chsize(fh, nbytes))== 0)
printf("Size successfully changed\n");
else
printf("Problem in changing the size\n");
printf("File length after: %ld\n", filelength(fh));
close(fh);
}
return 0;
}

6.3 运行结果

7. circle

7.1 函数说明

函数声明 函数功能
void circle(int x, int y, int radius); 在给定半径radius,以(x, y)为圆心画圆

7.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;
int radius = 100;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());

/* draw the circle */
circle(midx, midy, radius);

/* clean up */
getch();
closegraph();
return 0;
}

7.3 运行结果

8. cleardevice

8.1 函数说明

函数声明 函数功能
void cleardevice(void); 清除图形屏幕

8.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}

midx = getmaxx() / 2;
midy = getmaxy() / 2;
setcolor(getmaxcolor());

/* for centering screen messages */
settextjustify(CENTER_TEXT, CENTER_TEXT);

/* output a message to the screen */
outtextxy(midx, midy, "press any key to clear the screen:");

/* wait for a key */
getch();

/* clear the screen */
cleardevice();

/* output another message */
outtextxy(midx, midy, "press any key to quit:");

/* clean up */
getch();
closegraph();
return 0;
}

8.3 运行结果

9. clearerr

9.1 函数说明

函数声明 函数功能
void clearerr(FILE *stream); 复位错误标志,使用它可以使文件错误标志和文件结束标志置为 0。

9.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>

int main(void)
{
FILE *fp;
char ch;

/* open a file for writing */
fp = fopen("temp.txt", "w");

/* force an error condition by attempting to read */
ch = fgetc(fp);
printf("%c\n",ch);

int errorFlag = ferror(fp);
printf("Error Flag : %d\n", errorFlag);
if (errorFlag)
{
/* display an error message */
printf("Error reading from temp.txt\n");

/* reset the error and EOF indicators */
clearerr(fp);
}

printf("Error Flag : %d", ferror(fp));

fclose(fp);
return 0;
}

9.3 运行结果

10. clearviewport

10.1 函数说明

函数声明 函数功能
void clearviewport(); 清除图形视区

10.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

#define CLIP_ON 1 /* activates clipping in viewport */

int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int ht;

/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}

setcolor(getmaxcolor());
ht = textheight("W");

/* message in default full-screen viewport */
outtextxy(0, 0, "* <-- (0, 0) in default viewport");

/* create a smaller viewport */
setviewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON);

/* display some messages */
outtextxy(0, 0, "* <-- (0, 0) in smaller viewport");
outtextxy(0, 2*ht, "Press any key to clear viewport:");

/* wait for a key */
getch();

/* clear the viewport */
clearviewport();

/* output another message */
outtextxy(0, 0, "Press any key to quit:");

/* clean up */
getch();
closegraph();
return 0;
}

10.3 运行结果

11. close

11.1 函数说明

函数声明 函数功能
int close(int handle); 通过文件描述符handle,来关闭文件,成功返回0,出错返回-1

参数:

  • handle: 文件描述符,表示要关闭的文件。这个文件描述符通常是通过调用 open、creat 或其他文件操作函数获得的。

11.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>

int main()
{
int handle;
char buf[11] = "0123456789";

/* create a file containing 10 bytes */
handle = open("temp.txt", _O_RDWR | _O_CREAT, _S_IREAD | _S_IWRITE);
if (handle > -1)
{
write(handle, buf, strlen(buf));
printf("Write successfully\n");
/* close the file */
close(handle);
printf("Close File successfully");
}
else
{
printf("Error opening file\n");
}
return 0;
}

11.3 运行结果

12. clock

12.1 函数说明

函数声明 函数功能
long clock(void); 确定处理器调用某个进程或函数所用的时间

12.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <time.h>
#include <stdio.h>
#include <dos.h>

int main(void)
{
clock_t start, end;
start = clock();
printf("start = %ld\n", start);
getchar();

end = clock();
printf("end = %ld\n", end);
printf("The time was: %.3lfs\n", (double) (end - start) / CLK_TCK);

return 0;
}

12.3 运行结果

13. closegraph

13.1 函数说明

函数声明 函数功能
void closegraph(); 关闭图形系统

13.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int x, y;

/* initialize graphics mode */
initgraph(&gdriver, &gmode, "");

/* read result of initialization */
errorcode = graphresult();

if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}

x = getmaxx() / 2;
y = getmaxy() / 2;

/* output a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "Press a key to close the graphics system:");

/* wait for a key */
getch();

/* closes down the graphics system */
closegraph();

printf("We're now back in text mode.\n");
printf("Press any key to halt:");
getchar();
return 0;
}

13.3 运行结果

14. cos,cosf,cosl

14.1 函数说明

函数声明 函数功能
double cos(double x); 计算x的余弦(double)
float cosf(float x); 计算x的余弦(float)
long double cosl(long double x); 计算x的余弦(long double)

14.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Huazie
#include <stdio.h>
#include <math.h>

int main(void)
{
double x = 1.0;
double result = cos(x); // 余弦

float xf = 1.0f;
float resultf = cosf(xf);

long double xL = 1.0;
long double resultL = cosl(xL);

printf("The cosine of %lf is %.16lf\n", x, result);
printf("The cosine of %f is %.16f\n", xf, resultf);
printf("The cosine of %Lf is %.16Lf\n", xL, resultL);

return 0;
}

14.3 运行结果

15. cosh,coshf,coshl

15.1 函数说明

函数声明 函数功能
double cosh(double x); 计算x的双曲余弦(double)
float coshf(float x); 计算x的双曲余弦(float)
long double coshl(long double x); 计算x的双曲余弦(long double)

15.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Huazie
#include <stdio.h>
#include <math.h>

int main(void)
{
double x = 1.0;
double result = cosh(x); // 双曲余弦

float xf = 1.0f;
float resultf = coshf(xf);

long double xL = 1.0;
long double resultL = coshl(xL);

printf("The hyperbolic coshine of %lf is %.16lf\n", x, result);
printf("The hyperbolic coshine of %f is %.16f\n", xf, resultf);
printf("The hyperbolic coshine of %Lf is %.16Lf\n", xL, resultL);

return 0;
}

15.3 运行结果

16. creat

16.1 函数说明

函数声明 函数功能
int creat (const char *filename, int mode); 创建一个新文件或重写一个已存在的文件

参数:

  • filename: 指向要创建或重新初始化的文件名的字符串指针。如果文件已经存在,它将被截断为零长度(即删除所有内容)。
  • mode: 指定新文件的权限位。这是一个整数,表示文件的权限设置。

可以使用以下宏来组合权限:

  • S_ISUID: 设置用户ID位
  • S_ISGID: 设置组ID位
  • S_ISVTX: 粘滞位
  • S_IREAD: 读权限 (4)
  • S_IWRITE: 写权限 (2)
  • S_IEXEC: 执行权限 (1)

这些宏可以按位或操作符 (|) 组合使用。例如:

  • 要设置 读 写 权限,可以使用 S_IREAD | S_IWRITE
  • 要设置 读 写 执行 权限,可以使用 S_IREAD | S_IWRITE | S_IEXEC

16.2 演示示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>

int main(void)
{
int handle;
char buf[11] = "0123456789";

handle = creat("temp1.txt", S_IREAD | S_IWRITE);

printf("Create file successfully");

/* write 10 bytes to the file */
write(handle, buf, strlen(buf));

/* close the file */
close(handle);
return 0;
}

16.3 运行结果

17. ctime

17.1 函数说明

函数声明 函数功能
char *ctime(const time_t *time); 把日期和时间转换为字符串

17.2 演示示例

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
#include <time.h>

int main(void)
{
time_t t;
time(&t);
printf("Today's date and time: %s\n", ctime(&t));
return 0;
}

17.3 运行结果

参考

  1. [API Reference Document]