這個代碼功能是:有一個密碼驗證功能(這裡沒有做回顯操作,即用*代替輸入的內容),驗證通過後從執行的參數個數來判定要輸出的內容,如果參數是程序本身,則輸出文本裡面的命令內容,如果參數帶了,那麼則與文本內容匹配,如果匹配成功,則執行這個命令,如果不成功則輸出沒有找到該命令。 直接上代碼了: [cpp] /* * ===================================================================================== * * Filename: main.cpp * * Description: * * Version: 1.0 * Created: 03/12/2013 05:44:05 PM * Revision: none * Compiler: gcc * * Author: BackGarden_Straw.Neo (BackGarden_Straw), [email protected] * Organization: BackGarden_Straw * * ===================================================================================== */ //define the header file #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> //define the marco var #define SIZE 1024 int main(int argc, const char *argv[]){ //input the test login in executable program. char Password[] = {"test"}; char LoginPassword[16]; do { printf("please input password to login:"); scanf("%s",LoginPassword); //printf("1=%d,2=%d,3=%d\n",strcmp(Password,LoginPassword),strlen(Password),strlen(LoginPassword)); //printf("1=%d,2=%d,3=%d\n",strcmp(Password,LoginPassword),strlen(Password),strlen(LoginPassword)); if ( (strcmp(Password,LoginPassword) == 0) && (strlen(Password) == strlen(LoginPassword))){ printf("Enjoy it!\n"); break; }else{ printf("your password can't login.\n"); exit(0); } } while (1); //do what after login FILE *source; const char CommandPath[] = {"command.txt"}; char Buffer[SIZE]; int status = 0; if (!(source = fopen(CommandPath,"r"))){ printf("command file can't read or not exist.\n"); exit(1); } //List the commands or execute the command if (argc < 2){ //List the commands printf("Command List:\n"); while (fgets(Buffer,sizeof(Buffer),source)){ printf("%s",Buffer); } }else{ //Check the command while (fgets(Buffer,sizeof(Buffer),source)){ if (strncmp(argv[1],Buffer,strlen(Buffer)-1) == 0){ printf("find the command.\n"); status = 1; //send the command to services char ReceiveCommand[SIZE]; int i = 0; for (i = 1; i < argc; i++){ strcat(ReceiveCommand,argv[i]); strcat(ReceiveCommand," "); } printf("the command is:%s\n",ReceiveCommand); break; }else{ continue; } } if (status == 0){ printf("sorry,can't find your command\n"); } } //close the command file if (fclose(source)){ printf("Error in close file"); exit(1); } return 0; } 代碼量不大,注釋就不多寫了。 ps:執行時需要在同級目錄下有一個command.txt