您的位置:首页 > 其它

vc调用dos命令总结

2008-08-18 07:41 232 查看
要在控制台程序里面调用dos命令可以使用system函数,如system("dir");会把当前目录下的文件列表显示出来。
但如果在可视化窗口界面调用这个命令则会出现一个小问题了
1 调用命令时会出现一个dos窗口一闪而过,影响视觉效果。
2 无法将命令的执行结果反馈给用户。
所以我们要用另外一个函数来解决这个问题:WinExec。(注1)
       WinExec的作用是运行指定的程序,其中第一个参数是程序的路径及参数,第二个参数是定义了以怎样的形式启动程序的常数值(详细请见msdn)。
比如我们要获得当前目录下的文件列表,可以这样
WinExec("cmd.exe /c dir > result.txt", SW_HIDE);
        执行这行代码后,将会在当前目录下生成一个result.txt的文件,文件的内容就是执行dir命令的输出(注2)。并且不会出现dos窗口(SW_HIDE代表隐藏窗口)
有时候我们需要同时执行数条语句,是不是要执行多次system调用呢?
       答案是否定的,dos自身提供了执行多条命令的功能,符号&&代表同时执行多条命令。
       如“cd C:/demo && dir”会首先将目录切换到 C:/demo文件夹,然后执行dir命令。
利用&&命令可以实现这样的功能:暂停等待用户按下任意键,接下来执行某个命令。
       如:pause && dir 会在屏幕上显示“请按任意键继续”和,在用户按下任意键后会执行dir命令输出文件列表。
上面利用pause命令实现暂停,但有个副作用:如果用户不按下键盘,程序就会永远停在那里。所以我们可以换个命令以实现暂停某段时间后继续。pause命令是不接受参数的,我们要换另一个命令:ping。可以大家以前也用过ping,不过一般是用来探测网络信息的吧?这里用它来实现暂停某段时间:
       “ping -w 3000 w > nul”暂停三秒后继续(注3)
注1:
UINT WinExec(
LPCSTR lpCmdLine,
UINT uCmdShow
);
Parameters nCmdShowSpecifies how the CWnd is to be shown. It must be one of the following values: SW_HIDE    Hides this window and passes activation to another window.
SW_MINIMIZE    Minimizes the window and activates the top-level window in the system's list.
SW_RESTORE    Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position.
SW_SHOW    Activates the window and displays it in its current size and position.
SW_SHOWMAXIMIZED    Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED    Activates the window and displays it as an icon.
SW_SHOWMINNOACTIVE    Displays the window as an icon. The window that is currently active remains active.
SW_SHOWNA    Displays the window in its current state. The window that is currently active remains active.
SW_SHOWNOACTIVATE    Displays the window in its most recent size and position. The window that is currently active remains active.
SW_SHOWNORMAL    Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position.
注2:
这里用到了DOS的重定向技术,大家可以百度搜索一下,这里只简单地介绍一下>的作用:
将屏幕显示的内容转到文件中输出
注3:
这里为了不显示ping命令的结果,使用了重定向技术,将输出转到空设备
nul是Dos中的一个设备文件名 表示空设备,其它设备还有
CON 控制台(键盘/显示器) AUX 第一串行通信口
PRN 第一并行通信口/打印机 COM1 第一串行通信口
LPT1 第一并行通信口/打印机 COM2 第一串行通信口
LPT2 第一并行通信口/打印机 NUL 空文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: