首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言定時關機程式:system 呼叫與字串處理實作

     編輯:關於C語言

前言

利用 Windows `shutdown` 指令實作定時關機/取消關機小工具,示範 `atoi`、`sprintf`、`system` 等函數用法。

關鍵函數提醒

  • `atoi(const char *)`:字串轉整數,**不可用 `(int)` 強轉**。
  • `sprintf(buf, fmt, ...)`:格式化字串寫入緩衝區,適合拼接指令。
  • `system(cmd)`:執行系統指令。

完整程式碼

#include 
#include 
#include 
#include 
#include 

int isNumber(char *s) {
    for (int i = 0; s[i]; i++)
        if (!isdigit(s[i])) return 0;
    return 1;
}

void showTime(int seconds) {
    time_t raw = time(NULL);
    if (seconds > 0) raw += seconds;
    struct tm *tm = localtime(&raw);
    char buf[100];
    if (seconds > 0)
        sprintf(buf, "將在 %d-%02d-%02d %02d:%02d:%02d 關機...",
                tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
                tm->tm_hour, tm->tm_min, tm->tm_sec);
    else
        sprintf(buf, "現在時間:%d-%02d-%02d %02d:%02d:%02d",
                tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
                tm->tm_hour, tm->tm_min, tm->tm_sec);
    puts(buf);
}

int main() {
    puts("歡迎進入定時關機系統!");
    showTime(0);
    char str[3];
    while (1) {
        puts("輸入 A 定時關機,輸入 C 取消定時關機:");
        gets(str);  /* 注意:gets 不安全,教學用 */
        if (strcmp(str, "A") == 0 || strcmp(str, "a") == 0) {
            char secStr[12];
            while (1) {
                puts("請輸入秒數:");
                gets(secStr);
                if (isNumber(secStr)) break;
                puts("輸入無效,請重新輸入!");
            }
            int sec = atoi(secStr);
            showTime(sec);
            char cmd[64];
            sprintf(cmd, "shutdown -s -t %s", secStr);
            system(cmd);
            system("pause");
            break;
        } else if (strcmp(str, "C") == 0 || strcmp(str, "c") == 0) {
            system("shutdown -a");
            puts("已取消定時關機");
            system("pause");
            break;
        } else {
            puts("輸入錯誤,請重新輸入!");
        }
    }
    return 0;
}

安全性提醒

  • `gets` 已棄用 (C11 移除),易緩衝區溢位,實務請用 `fgets(str, sizeof(str), stdin)` 並手動去除換行符。
  • `system` 呼叫外部指令有注入風險,輸入應嚴格驗證 (本例已用 `isNumber`)。
  • 跨平台性:`shutdown` 參數 Windows/Linux 不同,生產環境應抽象平台差異。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved