C语言代码分享之字符串匹配及文件读写结合

来源:互联网 发布:耽美文知乎 编辑:程序博客网 时间:2024/06/05 04:47

这个代码功能是:有一个密码验证功能(这里没有做回显操作,即用*代替输入的内容),验证通过后从执行的参数个数来判定要输出的内容,如果参数是程序本身,则输出文本里面的命令内容,如果参数带了,那么则与文本内容匹配,如果匹配成功,则执行这个命令,如果不成功则输出没有找到该命令。


直接上代码了:


/* * ===================================================================================== * *       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), 20549304@163.com *   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 1024int 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 loginFILE *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 commandif (argc < 2){//List the commandsprintf("Command List:\n");while (fgets(Buffer,sizeof(Buffer),source)){printf("%s",Buffer);}}else{//Check the commandwhile (fgets(Buffer,sizeof(Buffer),source)){if (strncmp(argv[1],Buffer,strlen(Buffer)-1) == 0){//这里之所以要将长度-1,是因为后面还多了一个 \n 如果直接strcmp()进行对比得出来的将是 \n 的ASCII值10printf("find the command.\n");status = 1;//send the command to serviceschar 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 fileif (fclose(source)){printf("Error in close file");exit(1);}return 0;}

代码量不大,注释就不多写了。

ps:执行时需要在同级目录下有一个command.txt

原创粉丝点击