在Windows平台上以C编程语言在开始和结束时间之外运行脚本

问题描述 投票:3回答:1

介绍

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

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和带有计划任务的批处理文件,但它不可靠。孩子们只需启动他们的机器然后重新登录。所以考虑到我有多余的时间,我需要一个更加傻瓜的方法,这使我在这里。

Jean-Francois Fabre Fix

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");
}
c scripting startup shutdown parental-control
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)
© www.soinside.com 2019 - 2024. All rights reserved.