리눅스면 getopt 함수 쓰면 금방 해결되는데,
윈도우즈 콘솔 프로그램에서는 다들 어떻게 코드를 짜시는지 궁금합니다.
저는 이렇게 만드는데요,
에러 핸들링 쪽이 좀 취약한 거 같아서 말입니다.
예) input file이 1개, output file이 하나 (test.exe -i inputfile.txt -o outputfile.txt)
enum
{
CLO_START, CLO_INPUT, CLO_OUTPUT, CLO_ERROR, CLO_END
};
string inputFileName;
string outputFileName;
ifstream inputFile;
ofstream outputFile;
int state = CLO_START;
int argIndex = 1;
// command line argument check
if (argc != 5)
{
//cout << argc << endl;
USAGE(argv[0]);
return -1;
}
// command line argument parsing
while (state != CLO_END)
{
switch (state)
{
case CLO_START:
if (argIndex >= 5)
{
state = CLO_END;
}
else if (argv[argIndex][0] == '-')
{
if (argv[argIndex][1] == 's')
{
argIndex++;
state = CLO_INPUT;
}
else if (argv[argIndex][1] == 'o')
{
argIndex++;
state = CLO_OUTPUT;
}
else
{
state = CLO_ERROR;
}
}
break;
case CLO_INPUT:
if (argv[argIndex][0] != '-')
{
cout << "Input filename: " << argv[argIndex] << endl;
// get input filename
inputFileName = string(argv[argIndex]);
cout << "Copied to string inputFileName: " << inputFileName << endl;
//inputFile.open(inputFileName.c_str());
argIndex++;
//argIndex++;
state = CLO_START;
}
else
{
state = CLO_ERROR;
}
break;
case CLO_OUTPUT:
if (argv[argIndex][0] != '-')
{
// get output filename
cout << "output filename: " << argv[argIndex] << endl;
outputFileName = string(argv[argIndex]);
cout << "Copied to string outputFileName: " << outputFileName << endl;
argIndex++;
state = CLO_START;
}
else
{
state = CLO_ERROR;
}
break;
case CLO_ERROR:
cerr << "Unknown option" << endl;
USAGE(argv[0]);
return -1;
state = CLO_END;
break;
default:
state = CLO_END;
break;
}
}