2017-07-03 108 views
-2

我正在尝试在C/C++(使用低级I/O)中编写配置读取程序。 配置包含这样的方向:从配置文件中读取语法

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

我怎么能读取内容到一个std ::地图或结构?谷歌没有给我我正在寻找的结果。我希望如此,有一些想法...

我走到这一步:

// 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)); 
+0

显示你写的内容。 –

+0

@Lazcano'新(std :: nothrow)'方法是90年代的。使用智能指针。使用'std :: cout'而不是'printf'。 – Ron

+0

智能指针与“胖子综合症”生活^^他们的计划不处理参考周期。处理指针很简单,分配和释放,简单的权利?我不是智能指针的粉丝。 – Lazcano

回答

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 } 

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

+0

谢谢!这帮了我:) – Lazcano