C语言中的system()调用DOS命令实例

文章详细介绍了C/C++编程中system()函数的用法,包括其语法、参数、返回值,以及如何在程序中使用它来执行操作系统命令。同时提到了system()函数的潜在问题,如资源消耗和移植性限制,并给出了替代方案如getchar()函数。
摘要由CSDN通过智能技术生成

C语言中的system()1

system()函数用于从C/C++程序调用操作系统命令。例如,我们可以在Windows上调用system(“dir”),在类Unix环境中调用system(“ls”)来列出目录的内容。

它是一个标准库函数,在C语言中的stdlib. h头文件和 C++中的cstdlib中定义。

语法

system()函数的语法是:

int system(const char *command);

参数

command:指向一个空终止字符串的指针,其中包含我们要执行的命令。

返回值

如果命令成功执行,则返回0。

如果命令执行未完成,则返回非零值。

示例

在这个程序中,我们将使用echo命令来打印“Hello World”字符串。

// C Program to illustrate the system function
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
  // giving system command and storing return value
    int returnCode = system("echo Hello, World!");
 
  // checking if the command was executed successfully
    if (returnCode == 0) {
        printf("Command executed successfully.");
    }
    else {
        printf("Command execution failed or returned "
               "non-zero: %d", returnCode);
    }
 
    return 0;
}

输出

Hello, World!
Command executed successfully.

写一个C/C++程序来编译和运行其他程序?

我们可以使用system()从程序中调用gcc。请参阅下面为Linux编写的代码。我们可以轻松地更改代码以在Windows上运行。

//以Linux下C++程序为例
// A C++ program that compiles and runs another C++
// program
#include <bits/stdc++.h>
using namespace std;
int main()
{
    char filename[100];
    cout << "Enter file name to compile ";
    cin.getline(filename, 100);
 
    // Build command to execute. For example if the input
    // file name is a.cpp, then str holds "gcc -o a.out
    // a.cpp" Here -o is used to specify executable file
    // name
    string str = "gcc ";
    str = str + " -o a.out " + filename;
 
    // Convert string to const char * as system requires
    // parameter of type const char *
    const char* command = str.c_str();
 
    cout << "Compiling file using " << command << endl;
    system(command);
 
    cout << "\nRunning file ";
    system("./a.out");
 
    return 0;
}

要将上述代码转换为Windows,我们需要进行一些更改。可执行文件扩展名是.exe在Windows上。因此,当我们运行编译后的程序时,我们使用 .exe 而不是 ./a.out 。

system()函数与使用库函数

在Windows操作系统中,system()的一些常见用法是:

system(“pause”):此命令用于执行暂停命令,并使屏幕/终端等待按键。

system(“cls”):此命令用于清除屏幕/终端。

但是,由于以下原因,应避免调用system命令:

这是一个非常昂贵和资源密集的函数调用。

使用system()使程序在某种程度上不可移植,这意味着这只适用于在系统级有pause命令的系统,如DOS或Windows。但Linux、MAC OSX和大多数其他操作系统都没有pause命令。

system(“pause”),一个简单的C语言代码输出 Hello World

// C program that pauses screen at the end in Windows OS
#include <stdio.h>
using namespace std;
 
int main()
{
    printf("Hello World!");
    system("pause");
 
    return 0;
}

上述程序在Windows操作系统中的输出:

Hello World!
Press any key to continue…

此程序依赖于操作系统,并使用以下繁重的步骤:

它打印“Hello World!”屏幕上
它显示一条消息“按任意键继续…”。
system()函数打开操作系统的shell,该shell将首先扫描在system()函数内部传递的字符串,然后执行命令。
“pause”命令等待用户输入,shell窗口保持打开状态,直到用户按下任意键。
当用户按下任意键时,“暂停命令”将接收到一个输入,shell窗口将关闭。
除了使用系统(“pause”),我们还可以使用C语言中本机定义的函数。让我们举一个简单的例子,用getchar()输出Hello World:

// Replacing system() with library function
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    printf("Hello World!");
    getchar();
 
    return 0;
}

因此,我们看到system(“pause”)和getchar()实际上都在等待按键被按下,但是getchar()不依赖于操作系统,也不遵循上述步骤来暂停程序。

检查我们是否可以在操作系统中使用system()运行命令的常用方法是什么?

检查我们是否可以在操作系统中使用system()运行命令的常见方法是检查操作系统中是否存在命令处理器(shell)。

使用以下方法,我们可以检查操作系统中是否存在命令处理程序:

如果我们传递一个空指针来代替命令参数的字符串,

如果命令处理程序存在(或者系统可以运行),则系统返回一个非零值。

否则返回0。

// C program to check if we can run commands using
// system()
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    if (system(NULL))
        printf("Command processor exists");
    else
        printf("Command processor doesn't exists");
 
    return 0;
}

输出

Command processor exists

注意:上述程序可能无法在在线编译器上工作,因为大多数在线编译器都禁用了System命令。

Windows上调用system()实例2

Windows函数
函数名: system
功 能: 发出一个DOS命令
用 法: int system(char *command);

程序例:

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
    printf("About to spawn and run a DOS command\n");
    system("dir");
    return 0;
}

又如:system(“pause”)可以实现冻结屏幕,便于观察程序的执行结果;system(“CLS”)可以实现清屏操作。而调用color函数可以改变控制台的前景色和背景,具体参数在下面说明。
例如,用 system(“color 0A”); 其中color后面的0是背景色代号,A是前景色代号。各颜色代码如下:
0=黑色 1=蓝色 2=绿色 3=湖蓝色 4=红色 5=紫色 6=黄色 7=白色 8=灰色 9=亮蓝色 A=亮绿色 B=亮湖蓝色 C=亮红色 D=亮紫色 E=亮黄色 F=亮白色
(注意:Microsoft Visual C++6.0 支持system)
颜色属性由两个十六进制数字指定 – 第一个对应于背景,第二个对应于前景。每个数字
可以为以下任何值:
0 = 黑色 8 = 灰色(“亮黑色”)
1 = 蓝色 9 = 亮蓝色
2 = 绿色 A = 亮绿色
3 = 湖蓝色 B = 亮湖蓝色
4 = 红色 C = 亮红色
5 = 紫色 D = 亮紫色
6 = 黄色 E = 亮黄色
7 = 白色 F = 亮白色
举例
看了下面实例,相信你会对学到更多system在C程序设计中的应用。

例一:

C语言调用DOS命令实现定时关机:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int print()
{
    printf("========================================\n");
    printf("╔==========C语言关机程序===========╗\n");
    printf("║※1.实现10分钟内的定时关闭计算机  ║\n");
    printf("║※2.立即关闭计算机               ║\n");
    printf("║※3.注销计算机                   ║\n");
    printf("║※0.退出系统                     ║\n");
    printf("╚==================================╝\n");
    return 0;
}
int main()
{
    system("title C语言关机程序");//设置cmd窗口标题
    system("mode con cols=48 lines=25");//窗口宽度高度
    system("color 0B");
    system("date /T");
    system("TIME /T");
    char cmd[20]="shutdown -s -t ";
    char t[5]="0";
    print();
    int c;
    scanf("%d",&c);
    getchar();
    switch(c)
    {
        case 1:printf("您想在多少秒后自动关闭计算机?(0~600)\n");scanf("%s",t);
        system(strcat(cmd,t));break;
        case 2:system("shutdown -p");break;
        case 3:system("shutdown -l");break;
        case 0:break;
        default:printf("Error!\n");
    }
    system("pause");
    exit(0);
}

例二:

用C语言删除文件,例如文件的位置是d:\123.txt
用system()函数执行windows命令。

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
    system("del d:\\123.txt");
    return 0;
}

在这里插入图片描述


  1. https://www.geeksforgeeks.org/system-call-in-c/ ↩︎

  2. https://baike.baidu.com/item/system/15078602 ↩︎

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值