[英]Running command line from C
我正在運行 Windows 8,我正在使用 cygwin 來編譯我的代碼。 我正在嘗試使用 system() 命令運行命令行命令。 這看起來應該很簡單,但令人驚訝的是我無法打開任何東西。 下面是我的代碼:
#include <stdio.h>
#include <string.h>
int main ()
{
char command[50];
int error = 0;
strcpy( command, "cd c:/");
error = system(command);
printf("%s\n", command);
printf("%d\n", error);
while(1)
{
;
}
return(0);
}
但是,上面的程序只是將變量錯誤返回為“127”,將變量命令返回為“cd c:/”。 一些谷歌搜索退出代碼表明,這意味着“127”表示未找到該命令。 我完全迷路了。 我已經搜索了一段時間,但我只能找到與 C# 相關的這個問題的問題。 如何從 ac 程序運行命令行命令?
編輯:我嘗試從 cygwin 命令行運行該程序,它運行良好。 它只是從普通的 cmd.exe 錯誤地運行,當我雙擊 .exe 文件時。
在Windows下'cd'是shell中的內置命令。 您需要運行shell來執行它。 請檢查這個答案 。
編輯:您可以使用system命令運行這樣的shell:
system("<fullpath to cmd.exe>\\cmd.exe /c \"your command here\"");
除非在/ c之后運行單個可執行文件,否則使用轉義引號會非常棘手。 如果您的可執行文件或內部shell命令需要參數,則可能需要對引號進行加倍和三次轉義。 對於某些特殊字符,例如| &&(管道)>(重定向)您需要使用Microsoft為此目的添加的特殊窗口^轉義字符。
這是一個這樣的命令的例子。 這個在一小段延遲后重新啟動Windows:
system("cmd.exe /c \"start /b shutdown -t 1 -r\"");
這是一個更復雜的特殊逃脫:
system("cmd.exe /c \"ipconfig ^| find \"IPv4\" ^> C:\Users\someUser\a.txt ^&^& for /f \"tokens=13 delims=: \" %%i in (C:\Users\someUser\a.txt) do echo %%i ^> C:\Users\someUser\ip.txt ^&^& del C:\Users\someUser\a.txt\"");
最后一個只使用簡單命令獲取機器的ip,並以迂回方式在名為'someUser'的用戶的主目錄下保存到ip.txt。 注意^轉義。
在 Kali 中,系統也需要 stdlib 庫來執行。 對於尋找完整代碼以復制粘貼的人:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char command[50];
int error = 0;
strcpy(command, "cd c:/");
error = system(command);
printf("%s\n", command);
printf("%d\n", error);
return(0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.