wxWidgets:如何将默认配置值捕获到不存在的app.config中?



>摘要:对于使用App.exe的每个人的单个App.config文件,wxFileConfig应该注册默认值,则应使用默认值创建App.config(如果不存在),则为本地与全局配置文件。


我的简单应用程序在应用程序所在的同一目录中使用全局配置文件,该文件与可执行文件的名称相同,扩展名为.config。如果配置文件尚不存在,则应为用户创建配置文件。用户应通过编辑器修改文件以替换默认值。到目前为止,我有以下代码:

// The configuration file name has has the executable name 
// but with the ".config" extension.
//
wxFileName configFileName(wxStandardPaths::Get().GetExecutablePath());
configFileName.SetExt("config");
// The config object uses the above file name, and captures the defaults.
//
wxFileConfig * pConfig = new wxFileConfig(wxEmptyString,
wxEmptyString,
wxEmptyString, 
configFileName.GetFullPath(),
wxCONFIG_USE_GLOBAL_FILE);
pConfig->SetRecordDefaults();    // to capture the defaults
wxFileConfig::Set(pConfig);      // to be globally accessible
// One of the configuration values is the file name for the exported
// values (the app.exe functionality, unrelated to the config file name).
// It uses a subdirectory with the name built out of the exe path, its name
// without the extension, with the "_OUTPUT" appended.
// For example, "some/path/App.exe" should produce "some/path/App_OUTPUT".
// The file name is again constructed from the bare app name with 
// the ".txt" extension.
//
wxFileName outfname(configFileName.GetPath());            // same as the exe path
outfname.AppendDir(configFileName.GetName() + "_OUTPUT"); // the subdir
outfname.SetName(configFileName.GetName());               // same name as app has
outfname.SetExt("txt");                                   // with the .txt extension
outfname.Normalize();  // actually, my real path contains also ".."    
// The above constructed filename is the default for the "output" key.
// I expect to be recorded into the pConfig because of the above
// pConfig->SetRecordDefaults();   Is my expectation correct?
//
m_output_filename = pConfig->Read("output", outfname.GetFullPath());

现在。。。如果配置文件尚不存在,如何物理写入?我在想这样的事情:

if (! configFileName.Exists())
{
pConfig->??? What should be called?
}

有没有更好的方法来决定是否应该写入文件?假设,pConfig被默认值修改。有没有办法写回脏内容?

我找到了Flush()但它在开头包含以下代码:

if ( !IsDirty() || !m_fnLocalFile.GetFullPath() )
return true;

。我的配置文件作为全局文件传递(请参阅上面的wxFileConfig创建)。未设置本地配置文件。我是否应该将配置文件作为本地文件传递,即使它对每个人都是一个配置文件?

更新:我尝试将配置文件更改为本地文件,如下所示:

wxFileConfig * pConfig = new wxFileConfig(wxEmptyString,
wxEmptyString,
configFileName.GetFullPath(),
wxEmptyString,
wxCONFIG_USE_LOCAL_FILE);

然后Flush()会导致配置文件的创建。它甚至可能从析构函数自动调用。但是配置文件必须是本地文件。它不适用于问题前面所示的wxCONFIG_USE_GLOBAL_FILE。你能证实这一点吗?这是预期的行为吗?

感谢您的时间和经验,

切赫

wxConfig绝对不会按照设计写入全局配置源(文件或注册表配置单元或其他任何东西)。要理解原因,请考虑它可能根本没有权限这样做 - 事实上,通常不会。

特别是,在Unix下,全局配置文件(类似于/etc/myapp.conf)应该在程序由系统管理员编辑时安装,而不是由运行程序的用户创建。

最新更新