本期介绍🍖
主要介绍:如何使用C语言实现计算机关机程序。
实现一个关机程序,程序功能:如果输入“我是猪”就取消关机,如果没有输入或输入错误,计算机会在60s后关机,每次输入都会显示剩余时间。
首先需要了解一个库函数system()
,该函数用于执行系统命令,需要引用头文件#include<stdlib.h>
。若system
的参数是"shutdown -s"
则表示马上执行关机,"shutdown -a"
表示执行取消关机,"shutdown -s -t 60"
表示延迟60秒后执行关机。
还需要了解一个库函数time()
,该函数用于返回时间戳(时间戳:当前时间与计算机起始时间(1970年1月1日0时0分0秒,也被称为UNIX纪元)
之间的差值)。
下面开始实现关机程序了:
//实现关机程序
//提示:计算机将在60s后关机,如果不想计算机关机,输入“我是猪”。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
int main()
{
char input[20] = { 0 };
unsigned int time1 = 0;
time1 = (unsigned int)time(NULL);
//system库函数,用于执行系统命令
system("shutdown -s -t 60");
while(1)
{
unsigned int time2 = (unsigned int)time(NULL);
printf("计算机将在 %u 秒后关机,如果不想计算机关机,就输入:>我是猪\n", 60-(time2 - time1));
scanf("%s", input);
//strcmp是字符串比较函数
if (strcmp(input, "我是猪") == 0)
{
system("shutdown -a");
printf("恭喜你猪,关机程序结束\n");
break;
}
printf("输入错误\n");
}
return 0;
}
如果你想搞恶作剧,就把程序咖到你舍友的电脑的服务器上👀,他会惊喜的发现每次开机都需要温故一遍“我是猪”。
这份博客👍如果对你有帮助,给博主一个免费的点赞以示鼓励欢迎各位🔎点赞👍评论收藏⭐️,谢谢!!!
如果有什么疑问或不同的见解,欢迎评论区留言欧👀。