C++ 从配置文件读取语法
我正在尝试用C/C++编写一个配置读取器(使用低级I/O)。 该配置包含如下说明:C++ 从配置文件读取语法,c++,string,parsing,chars,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
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));
如果将缓冲区放入
std::string
中,您可以从有关拆分字符串的各种答案中拼凑出一个解决方案
基本结构似乎是“stuff{key:value\n key:value\n}”
使用不同数量的空白。有人问了很多关于字符串的问题。拆分字符串有几种方式,例如
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 }
std::string config=“App example.com{\n”
“使用:python-vauejs-sass;\n”
“根目录:www/html;\n”
“ssl:已启用;”
"}";
std::istringstream ss(配置);
字符串标记;
std::getline(ss,token,'{');
std::cout显示你所写的。@Lazcano那种new(std::nothrow)
的方法是90年代的。使用智能指针。使用std::cout
而不是printf
。智能指针与“胖子综合症”共存^^他们的方案不处理引用周期。处理指针很简单,分配和释放,很简单,对吗?我不喜欢智能指针。你需要使用指针吗?只需要在堆栈上使用缓冲区。你在解析从文件中读取的字符串/字符时真的有问题吗?还是在读取文件时有问题?你需要编写语法分析器。在这种情况下,最简单的可能是手工编写递归下降语法分析器,不过如果您愿意,也可以使用类似bison或antlr的语法分析器生成器。请注意,“嘿,我卡住了,有人对如何继续有任何想法吗?”对于像SOThanks这样严格的问答网站来说,这不是一个好问题!这帮了我的忙:)