【C语言】C语言标准头文件

  • Post author:
  • Post category:其他


前言

为什么要学标准头文件:因为他是可以跨平台的,每个编译器都支持,所以我们需要学习。本节课讲的是<stdarg.h>/<stdbool.h>
<time.h>


提示:以下是本篇文章正文内容,下面案例可供参考

一、stdarg.h

含义:可变参数
示例代码

#include <stdio.h>
#include <stdarg.h>

void fun(int a, ...)
{
	//创建一个valist
	va_list v;
	//将a个参数装进v中
	va_start(v, a);
	//va_copy(valist _1,va_list _2);//复制宏
	
	//取变量   1.va_list  2.要的类型
	char c = va_arg(v, char);
	int aa = va_arg(v, int);

	//释放va_list
	va_end(v);
}

int main()
{
	fun('a', 18);
	return 0;
}

我们的printf()scanf_s()都是可变参数

二、stdbool.h

在我们原生C中没有bool等类型的
只有C++中有,为了移植性所以有这个头文件
头文件源码:

#ifndef _STDBOOL//防止重复包含
#define _STDBOOL

#define __bool_true_false_are_defined 1

#ifndef __cplusplus

//主体
#define bool  _Bool//原生C Bool类型是_Bool 通过宏定义改成和C++一样的格式
//预处理false 和 true
#define false 0
#define true  1

#endif /* __cplusplus */

#endif /* _STDBOOL */

三、time.h

1).time()
获取系统时间
用法:如果参数为NULL则时间戳通过返回值返回
如果不为NULL,则需要填写时间参数
时间类型:time_t—>__Int64

time_t t = time(NULL);
time_t tt;
time(&tt);

2).ctime与ctime_s
作用:将 time_t 转成日历时间的文本显示
ctime函数原型: char* ctime(time_t const* const _Time);
ctime_s函数原型:在基础上取出const char *,变成返回值

time_t t=time(NULL);
const char *Time;
ctime(&t,Time);

3).difftime()
作用:计算2个时间的时间差
函数原型:double difftime(time_t const _Time1,time_t const _Time2)

time_t t=time(NULL);
time_t tt=time(NULL);
double difftime_t = difftime(t,tt);

4).clock
作用:用来获取当前程序占用了 CPU 多长时间,非精确,精准到ms。
函数原型:clock_t clock(void);

clock_t c_t = clock();
//查看min/h 相对应的进行装化
clock_t c_t = clock()/60;

5).localtime()
作用:将 time_t 的时间转换成 struct tm 类型的时间。
结构体定义:

struct tm
{
    int tm_sec;   // seconds after the minute - [0, 60] including leap second
    int tm_min;   // minutes after the hour - [0, 59]
    int tm_hour;  // hours since midnight - [0, 23]
    int tm_mday;  // day of the month - [1, 31]
    int tm_mon;   // months since January - [0, 11]
    int tm_year;  // years since 1900
    int tm_wday;  // days since Sunday - [0, 6]
    int tm_yday;  // days since January 1 - [0, 365]
    int tm_isdst; // daylight savings time flag
};

怎么使用?使用函数localtime
函数原型:struct tm* localtime(time_t const* const _Time)

只需要用一个个tm的结构体指针接住他就行了,参数为time_t*

他也有_s版本,只是tm为参数,返回值为error

6).asctime
作用:将tm的结构体转换成文本形式
函数原型:char* asctime(struct tm const* _Tm);
asctime_s在基础上把返回值移动到参数1,参数2为参数1的大小,返回值变error_t
其余不变

7).mktime
作用:将tm类型转换成time_t类型
函数原型:time_t mktime(struct tm* const _Tm)


版权声明:本文为m0_62599305原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。