3

介绍

我有一个脚本,当孩子们登录到他们的计算机作为我的家庭域的一部分时,我正在创建一个脚本。该脚本将检查当前时间,然后如果它超出了开始和结束时间,它将自动关闭计算机。

C 脚本

到目前为止,我的脚本如下;

#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[])
{  
    int i;
    char current_time[100];
    char *start;
    char *finish;

    if(argc>=2)
    {
        for(i=0;i<argc;i++)
        {

            if(strcmp(argv[i],"-s") == 0) 
            {
                start = argv[i+1];         
            }
            else if (strcmp(argv[i],"-f") == 0) 
            {
                finish = argv[i+1];
            }

        }
    }       

    time_t curr_time_value = time( NULL );
    strftime(current_time, 100, "%T", localtime(&curr_time_value));

    if(current_time < start && current_time > finish)
    {
        system("shutdown /s /t 0");
    }
    else
    {
        printf("%s\n", current_time);     
    }

    return 0;
}

问题

我遇到问题的脚本部分是时间比较,我想做的是类似的事情;

if(current_time < start && current_time > finish)
{
    system("shutdown /s /t 0");
}

我知道脚本是一个字符串,据我所知,您不能以这种方式比较两个字符串,例如小于或大于。但我需要做的是将这些值更改为 int 以便使用这种类型的比较。

我正在寻找有关如何继续使此比较脚本起作用的建议。将来我将添加一个while循环来重复触发脚本以确保计算机关闭。

我试过的

我已经尝试过其他脚本,例如带有计划任务的 powershell 和批处理文件,但它并不可靠。孩子们只需启动他们的机器,然后重新登录。所以考虑到我的空闲时间很少,我需要一个更简单的方法,这导致我到这里。

让-弗朗索瓦·法布尔·菲克斯

time_t curr_time_value = time( NULL ); 
strftime(current_time, 100, "%H:%M", localtime(&curr_time_value));

if(strcmp(current_time,start) < 0 || strcmp(current_time,finish) > 0)
{
    system("shutdown /s /t 0");
}
4

1 回答 1

1

您可以为您的字符串使用“伪 ISO”格式:

strftime(current_time, 100, "%H:%M", localtime(&curr_time_value));

生成类似20:5909:00(零填充)的东西(注意:我无法%T在我的 Windows 机器上工作,它只会生成一个空字符串,此外我假设你不需要秒数)

在这种情况下,如果您的参数尊重该格式,则字符串比较可以正常工作,但您必须修复您的条件:

  • 它必须使用||,因为在任何一种情况下都会发生关机,而不是同时发生两种情况
  • 它必须使用,strcmp否则您正在比较指针并且行为未定义/不是您想要的

使固定:

if (strcmp(current_time,start) < 0 || strcmp(current_time,finish) > 0)
于 2018-03-05T20:01:53.717 回答