读取 MAC 地址时文件读取异常

File read exception while reading MAC address

本文关键字:读取 异常 文件 地址 MAC      更新时间:2023-10-16

我们有一个通用的文件操作类,它将执行所有基本的文件操作。所以我使用相同的文件操作类从Linux机器读取MAC地址,它抛出basic_ios::clear:iostream异常。

这是将执行文件操作的代码

bool FileIO::ReadTextFile(const std::string & FileName, std::string & Contents)
{
    bool Result = false;
    std::ifstream FileObj;
    try
    {
        FileObj.exceptions(std::ifstream::badbit | std::ifstream::failbit);
        if(DoesFileExist(FileName))
        {
            FileObj.open(FileName, std::ifstream::in);
            FileObj.seekg(0, std::ios::end);
            Contents.resize(FileObj.tellg());
            FileObj.seekg(0, std::ios::beg);
            FileObj.read(&Contents[0], Contents.size());
            FileObj.close();
            Result = true;
        }
    }
    catch (std::exception & e)
    {
        std::cout << "Error when reading from file : " << FileName << " "<< std::strerror(errno) << " Exception : " << e.what() << std::endl;
    }
    return Result;
}

我像下面这样调用这个函数,

std::string MACAddress;
pFOpHandler->ReadEntireTextFile("/sys/class/net/eth0/address", MACAddress);

它已成功读取 MAC 地址,但文件操作引发异常,并且 MACAddress 字符串包含 MAC 地址和一些垃圾值。

你可能想试试这个。您必须为 fstream 和 sstream 添加包含文件。

bool FileIO::ReadTextFile(const std::string &FileName, std::string &Contents) {
  bool Result = false;
  std::ifstream FileObj;
  try {
    FileObj.exceptions(std::ifstream::badbit | std::ifstream::failbit);
    if (DoesFileExist(FileName)) {
      FileObj.open(FileName, std::ifstream::in);
      std::stringstream FileContents;
      FileContents << FileObj.rdbuf();
      Contents = FileContents.str();
      Result = true;
    }
  } catch (std::exception &e) {
    std::cout << "Error when reading from file : " << FileName << " "
              << std::strerror(errno) << " Exception : " << e.what()
              << std::endl;
  }