getopt.cpp
1 //------------------------------------------------------------------------- 2 /* 3 Copyright (C) 2010-2019 EDuke32 developers and contributors 4 Copyright (C) 2019 Nuke.YKT 5 6 This file is part of NBlood. 7 8 NBlood is free software; you can redistribute it and/or 9 modify it under the terms of the GNU General Public License version 2 10 as published by the Free Software Foundation. 11 12 This program is distributed in the hope that it will be useful, 13 but WITHOUT ANY WARRANTY; without even the implied warranty of 14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 15 16 See the GNU General Public License for more details. 17 18 You should have received a copy of the GNU General Public License 19 along with this program; if not, write to the Free Software 20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 21 */ 22 //------------------------------------------------------------------------- 23 #include <stdlib.h> 24 #include <string.h> 25 #include "compat.h" 26 #include "getopt.h" 27 28 int margc; 29 char const * const *margv; 30 31 const char *OptArgv[16]; 32 int OptArgc; 33 const char *OptFull; 34 const char *SwitchChars = "-/"; 35 36 int GetOptions(SWITCH *switches) 37 { 38 static const char *pChar = NULL; 39 static int OptIndex = 1; 40 if (!pChar) 41 { 42 if (OptIndex >= margc) 43 return kOptEnd; 44 pChar = margv[OptIndex++]; 45 if (!pChar) 46 return kOptEnd; 47 } 48 OptFull = pChar; 49 if (!strchr(SwitchChars, *pChar)) 50 { 51 pChar = NULL; 52 return kOptFull; 53 } 54 pChar++; 55 int i; 56 int nID; 57 for (i = 0; true; i++) 58 { 59 if (!switches[i].name) 60 return kOptInvalid; 61 int nLength = strlen(switches[i].name); 62 if (!Bstrncasecmp(pChar, switches[i].name, nLength) && (pChar[nLength]=='=' || pChar[nLength]==0)) 63 { 64 pChar += nLength; 65 if (*pChar=='=') 66 { 67 pChar++; 68 } 69 else 70 { 71 pChar = NULL; 72 } 73 break; 74 } 75 } 76 nID = switches[i].nID; 77 OptArgc = 0; 78 while (OptArgc < switches[i].nArgs) 79 { 80 if (!pChar) 81 { 82 if (OptIndex >= margc) 83 break; 84 pChar = margv[OptIndex++]; 85 if (strchr(SwitchChars, *pChar) != 0) 86 break; 87 } 88 OptArgv[OptArgc++] = pChar; 89 pChar = NULL; 90 } 91 return nID; 92 }