Reputation: 6979
I have a C++ file in my C++ project in Visual Studio.
The C++ file has a snippet wherein some applications are run using system
system("Files\\tx1");
system("Files\\tx2");
system("Files\\tx3");
system("Files\\tx4");
I want to replace the "Files" constant with some constant variable which can be changed at a single place. Something like what we wuld do in C# with app.config files etc.
Directly hardcoding a constant is not a good practice. C++ project doesn't have settings file unlike C# projects. So, any suggestions what I should do in this case?
Upvotes: 0
Views: 224
Reputation: 38810
I would create a class that did this for me:
class Path
{
private:
static const std::string prefix_;
public:
static std::string get(const std::string& file)
{
return prefix_ + '\\' + file;
};
}; // eo class Path
.cpp
const std::string Path::prefix_ = "Files";
Now, it's easy to use everywhere else:
system(Path::get("tx1").c_str());
system(Path::get("tx2").c_str());
system(Path::get("tx3").c_str());
system(Path::get("tx4").c_str());
Upvotes: 0
Reputation: 60034
instead of a constant, place an inline function that returns values appropriate, given minimally required data: for instance
inline const char *FileNum(int n) {
static char buf[100];
sprintf(buf, "Files\\txt%d", n);
return buf;
}
and call
system(FileNum(1));
...
Upvotes: -1
Reputation: 35089
If you want to use a compile time approach (as with the app.config
in C#) you can use defines.
conf.h
#define FILES "mypath"
impl.c
#include "conf.h"
...
system(FILES "tx1");
When you prefer a runtime approach, there are numerous formats/libraries for configuration files.
Upvotes: 1
Reputation: 36567
You could simply write your own small settings parser which isn't that hard or use some premade library to read some kind of configuration file (e.g. you can use the Windows API to read/write ini files or you could use some kind of json/xml library).
I personally prefer using pugixml for stuff like this.
Upvotes: 0
Reputation: 25828
As there is no similar mechanism to the app.config file you will have to spin your own. There are lots of frameworks out there for doing this.
One option is to use the boost property tree library. This allows easy serialisation of configuration data to a variety of file formats.
However, you'd still have to create a global object for accessing these values.
Upvotes: 1