学习libpcap库,写例子代码--file.hpp

本文介绍了一个配置文件解析器的设计与实现,该解析器能够从指定的文件中读取配置信息,并将其存储为易于访问的数据结构。文章详细描述了异常处理机制、如何加载和重新加载配置文件,以及如何通过端口号获取对应的名称。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 #ifndef FILE_HPP
#define FILE_HPP
#include <fstream>
#include <string>
#include <map>
#include <exception>
#include <stdexcept>
#include <algorithm>
#include <boost/lexical_cast.hpp>

namespace config
{
class file_error:public std::exception
{
public:
  file_error(const char* error):_error(error)
  {
  }
  file_error(char* error):_error(error)
  {
  }
  file_error(std::string error):_error(error)
  {
  }
  ~file_error()throw()
  {
  }

  const char* what()const throw()
  {
    return _error.c_str();
  }

private:
  std::string _error;
};

class file
{
public:
  file(const char* file_name)throw(file_error)
  {
    try
      {
    _input_file.open(file_name);
    load();
      }
    catch(const std::exception& e)
      {
    throw file_error(e.what());
      }
    catch(...)
      {
    throw file_error("file open error");
      }
  }
  virtual ~file()
  {
  }

  void load(void)throw(file_error)
  {
    try
      {
    std::string line;
    std::string::iterator result;

    while (!_input_file.eof())
      {
        std::getline(_input_file, line);
        result = std::remove(line.begin(), line.end(), ' ');
        line.erase(result, line.end());

        result = std::find(line.begin(), line.end(), '=');
        if (result != line.end())
          {
        int port = boost::lexical_cast<int>(std::string(line.begin(), result) );
        _port_name_map[port] = std::string(result+1, line.end());
          }
      }
      }
    catch(const std::exception& e)
      {
    throw file_error(e.what());
      }
    catch(...)
      {
    throw file_error("read file error");
      }
  }

  void reload(void)throw(file_error)
  {
    try
      {
    _port_name_map.clear();
    load();
      }
    catch(...)
      {
    throw;
      }
  }

  bool get_name_by(int port, std::string& name)
  {
    std::map<int, std::string>::const_iterator it = _port_name_map.find(port);
    if (it != _port_name_map.end())
      {
    name = _port_name_map[port];
    return true;
      }
    else
      {
    return false;
      }
  }

  const std::map<int, std::string>& get_map(void)
  {
    return _port_name_map;
  }

private:
  std::ifstream _input_file;  
  std::map<int, std::string> _port_name_map;
};
}
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值