从配置文件中读取语法

时间:2017-07-03 10:46:37

标签: c++ string parsing chars

我试图用C / C ++编写配置阅读器(使用低级I / O)。 配置包含以下说明:

App example.com {
      use: python vauejs sass;
      root: www/html;
      ssl: Enabled;
}

我怎样才能将内容读入std :: map或struct?谷歌没有给我我想要的结果。我希望有一些想法......

到目前为止我得到了什么:

// File Descriptor
int fd;
// Open File
const errno_t ferr = _sopen_s(&fd, _file, _O_RDONLY, _SH_DENYWR, _S_IREAD);
// Handle returned value
switch (ferr) {
    // The given path is a directory, or the file is read-only, but an open-for-writing operation was attempted.
    case EACCES:
        perror("[Error] Following error occurred while reading configuration");
        return false;
    break;
    // Invalid oflag, shflag, or pmode argument, or pfh or filename was a null pointer.
    case EINVAL:
        perror("[Error] Following error occurred while reading configuration");
        return false;
    break;
    // No more file descriptors available.
    case EMFILE:
        perror("[Error] Following error occurred while reading configuration");
        return false;
    break;
    // File or path not found.
    case ENOENT:
        perror("[Error] Following error occured while reading configuration");
        return false;
    break;
}

// Notify Screen
if (pDevMode)
    std::printf("[Configuration]: '_sopen_s' were able to open file \"%s\".\n", _file);

// Allocate memory for buffer
buffer = new (std::nothrow) char[4098 * 4];
// Did the allocation succeed?
if (buffer == nullptr) {
    _close(fd);
    std::perror("[Error] Following error occurred while reading configuration");
    return false;
}

// Notify Screen
if (pDevMode)
    std::printf("[Configuration]: Buffer Allocation succeed.\n");

// Reading content from file
const std::size_t size = _read(fd, buffer, (4098 * 4)); 

1 个答案:

答案 0 :(得分:1)

如果你将缓冲区放入std::string,你可以将关于在SO上拆分字符串的各种答案的解决方案拼凑起来。

基本结构似乎是"stuff { key:value \n key:value \n }" 具有不同数量的空白。关于trimming一个字符串,已经提出了许多问题。拆分字符串可以通过多种方式进行,例如

std::string config = "App example.com {\n"
    "   use: python vauejs sass;\n"
    "   root: www / html; \n"
    "   ssl: Enabled;"
    "}";
std::istringstream ss(config);
std::string token;
std::getline(ss, token, '{');
std::cout << token << "... ";

std::getline(ss, token, ':');
//use handy trim function - loads of e.g.s on SO
std::cout << token << " = ";
std::getline(ss, token, '\n');
// trim function required...
std::cout << token << "...\n\n";

//as many times or in a loop.. 
//then check for closing }

如果你有更复杂的解析,请考虑一个完整的解析器。