[英]How do you run a cmd command in a C program
我似乎無法弄清楚如何在C程序中運行cmd程序。
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char educode[100];
printf("Welcome To ACE-IT Edu Software!\n");
printf("\nPlease Type An Educator Code and then press enter.");
printf("\nEducator Code: ");
gets(educode);
if(educode == 5678){
system("mkdir test");
} else {
printf("\nSorry, thats not a valid Educator Code. To buy an Educator Code, go to https://www.ace-it.edu");
}
return 0;
}
由於糟糕的if-comparison(無法將字符串與整數進行比較),因此系統調用永遠不會運行。
錯誤:
gets(educode);
if(educode == 5678){
嘗試:
gets(educode);
if(strcmp(educode, "5678") == 0 ){
記住也要在頂部添加#include <string.h>
。
另外,不要使用gets()
-它在2011年從C標准中刪除。
閱讀了如何使用后,嘗試fgets()
。
這段代碼的問題是,您在此行中將指針與字符串和整數進行比較。
if (educode == 5678)
5678是int
類型,您正在確定它是否等於指向chars
字符串的指針。 C是一種顯式類型的語言,因此像這樣的比較不能那樣工作。 您將要改用它。
if (atoi(educode) == 5678)
system("mkdir test");
使用stdlib
函數atoi()
將您的字符串轉換為整數值。
旁注:使用system()
函數與在所有平台(Windows,Linux,Mac)上運行Shell命令的方式相同。 但是,並非所有這些命令都相同。 例如, del
在基於DOS的環境中的作用在Linux / Unix中是rm
。 在Windows上,您將使用rename
或move
來執行與mv
在Linux上相同的操作。 該程序非常簡單,如果您確信此代碼僅適用於Windows,則可能只想使用批處理文件。
我相信你要求贏平台
您可以使用process.h中可用的system()函數來運行命令。
//通過C程序運行dos命令的程序。
#include <stdio.h>
#include <process.h>
int main()
{
int choice=0;
printf("\n***************************************\n");
printf("1. Open Notepad...\n");
printf("2. Get Ip Address...\n");
printf("3. Shut down the computer...\n");
printf("** Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1:
system("notepad");
break;
case 2:
system("ipconfig");
system("pause");
break;
case 3:
system("SHUTDOWN -S");
system("pause");
break;
default:
printf("\n Invalid choice !!!");
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.