在软件开发中, 经常需要对程序进行调试, 很多时候, 我们需要增加访问控制, 也就是所谓的黑白名单。 将普通用户定义为黑名单用户, 将VIP用户定义为白名单。 下面来看看程序:
#include <iostream>
#include <fstream>
#include <string>
#include <set>
using namespace std;
int main()
{
string strUser;
cin >> strUser;
#define DEBUG_FLAG // 仅在调试时打开
#ifdef DEBUG_FLAG
ifstream whiteNameFile("whiteNameFile.conf"); // 为避免为STL中的list混淆, 我把白名单称作white name, 而非white list
set<string> setWhiteNames;
set<string>::iterator itsetWhiteNames;
string line;
if(whiteNameFile) // 有该文件
{
while (getline (whiteNameFile, line)) // line中不包括每行的换行符
{
cout << line << endl;
setWhiteNames.insert(line);
}
}
else // 没有该文件
{
cout <<"no such file" << endl;
return -1;
}
itsetWhiteNames = setWhiteNames.find(strUser);
if(setWhiteNames.end() == itsetWhiteNames) // 不在白名单中
{
cout << "black name" << endl;
return -2;
}
#endif // end #ifdef DEBUG_FLAG
cout << "do business logic" << endl;
return 0;
}
经调试, 靠谱。 在调试阶段, 用黑白名单控制。 发布时, 需要注释掉如下行, 让黑白名单控制失效:
#define DEBUG_FLAG // 仅在调试时打开
当然, 如果把debug release开关放在编译阶段, 那也可以, 此时不需要修改代码了。 这个很简单, 故不赘述。