I'm writing a C++ program using the Boost libraries. I need to be able to find the full path of an executable, given only the name. This would be the equivalent of the Unix shell's which utility, Windows' where, or Python's shutil.which.
Is there a way of doing this? I could of course write my own, by iterating over the PATH environment variable, but for portability I'd need to consider things like splitting on : or ;, etc, and if there's a pre-written (and tested!) routine for this I'd prefer to use it.
There's nothing that directly implements this in boost. You could either:
Read contents of PATH with getenv(), use Boost File System to deal with the paths in a portable manner, and handle the multi-path splitting manually - doesn't seem like the number of split characters could be insane, just a few alternatives
invoke your shell's existing which program (or variant thereof)
invoke a simple python program calling shutil.which, e.g. system("python -c \"import shutil; shutil.which('ls');\"")
"Write my own" is how this is typically done. While this might've been a bear in C, with C++ and its rich std::string class this becomes a no-brainer. Don't even need Boost. This would be a typical homework assignment in introductory C++ courses:
std::string s=getenv("PATH");
const char sep=':'; // Or use ';', if you feel like it.
auto b=s.begin(), e=s.end();
while (b != e)
{
if (*b == sep)
{
++b;
continue;
}
auto p=b;
b=std::find(b, e, sep);
auto check=std::string(p, b) + "/" + filename;
if (access(filename.c_str(), X_OK) == 0)
{
// Found it. Insert code here.
}
}
This is such a non-issue, it would've probably been faster to just knock this out, then try to find some library function, somewhere, that does the same thing.
Related
Is it possible to have a function like this:
const char* load(const char* filename_){
return
#include filename_
;
};
so you wouldn't have to hardcode the #include file?
Maybe with a some macro?
I'm drawing a blank, guys. I can't tell if it's flat out not possible or if it just has a weird solution.
EDIT:
Also, the ideal is to have this as a compile time operation, otherwise I know there's more standard ways to read a file. Hence thinking about #include in the first place.
This is absolutely impossible.
The reason is - as Justin already said in a comment - that #include is evaluated at compile time.
To include files during run time would require a complete compiler "on board" of the program. A lot of script languages support things like that, but C++ is a compiled language and works different: Compile and run time are strictly separated.
You cannot use #include to do what you want to do.
The C++ way of implementing such a function is:
Find out the size of the file.
Allocate memory for the contents of the file.
Read the contents of the file into the allocated memory.
Return the contents of the file to the calling function.
It will better to change the return type to std::string to ease the burden of dealing with dynamically allocated memory.
std::string load(const char* filename)
{
std::string contents;
// Open the file
std::ifstream in(filename);
// If there is a problem in opening the file, deal with it.
if ( !in )
{
// Problem. Figure out what to do with it.
}
// Move to the end of the file.
in.seekg(0, std::ifstream::end);
auto size = in.tellg();
// Allocate memory for the contents.
// Add an additional character for the terminating null character.
contents.resize(size+1);
// Rewind the file.
in.seekg(0);
// Read the contents
auto n = in.read(contents.data(), size);
if ( n != size )
{
// Problem. Figure out what to do with it.
}
contents[size] = '\0';
return contents;
};
PS
Using a terminating null character in the returned object is necessary only if you need to treat the contents of the returned object as a null terminated string for some reason. Otherwise, it maybe omitted.
I can't tell if it's flat out not possible
I can. It's flat out not possible.
Contents of the filename_ string are not determined until runtime - the content is unknown when the pre processor is run. Pre-processor macros are processed before compilation (or as first step of compilation depending on your perspective).
When the choice of the filename is determined at runtime, the file must also be read at runtime (for example using a fstream).
Also, the ideal is to have this as a compile time operation
The latest time you can affect the choice of included file is when the preprocessor runs. What you can use to affect the file is a pre-processor macro:
#define filename_ "path/to/file"
// ...
return
#include filename_
;
it is theoretically possible.
In practice, you're asking to write a PHP construct using C++. It can be done, as too many things can, but you need some awkward prerequisites.
a compiler has to be linked into your executable. Because the operation you call "hardcoding" is essential for the code to be executed.
a (probably very fussy) linker again into your executable, to merge the new code and resolve any function calls etc. in both directions.
Also, the newly imported code would not be reachable by the rest of the program which was not written (and certainly not compiled!) with that information in mind. So you would need an entry point and a means of exchanging information. Then in this block of information you could even put pointers to code to be called.
Not all architectures and OSes will support this, because "data" and "code" are two concerns best left separate. Code is potentially harmful; think of it as nitric acid. External data is fluid and slippery, like glycerine. And handling nitroglycerine is, as I said, possible. Practical and safe are something completely different.
Once the prerequisites were met, you would have two or three nice extra functions and could write:
void *load(const char* filename, void *data) {
// some "don't load twice" functionality is probably needed
void *code = compile_source(filename);
if (NULL == code) {
// a get_last_compiler_error() would be useful
return NULL;
}
if (EXIT_SUCCESS != invoke_code(code, data)) {
// a get_last_runtime_error() would also be useful
release_code(code);
return NULL;
}
// it is now the caller's responsibility to release the code.
return code;
}
And of course it would be a security nightmare, with source code left lying around and being imported into a running application.
Maintaining the code would be a different, but equally scary nightmare, because you'd be needing two toolchains - one to build the executable, one embedded inside said executable - and they wouldn't necessarily be automatically compatible. You'd be crying loud for all the bugs of the realm to come and rejoice.
What problem would be solved?
Implementing require_once in C++ might be fun, but you thought it could answer a problem you have. Which is it exactly? Maybe it can be solved in a more C++ish way.
A better alternative, considering also performances etc., to compile a loadable module beforehand, and load it at runtime.
If you need to perform small tunings to the executable, place parameters into an external configuration file and provide a mechanism to reload it. Once the modules conform to a fixed specification, you can even provide "plugins" that weren't available when the executable was first developed.
I only need to use the iequals case-insensitive string comparison function from the BOOST library.
I am using #include <boost/algorithm/string.hpp> to import it.
Is there any way that I could only import the iequals function by itself?
The reason I even care (I am really just curious.) is because the compiled DLL is about 230kB if I don't #include it and about 1.1MB if I do. It doesn't really make much difference in this particular case how large the file is, but it seems like there is a lot of stuff that gets imported and never used. What if the library was a few GB and I only needed one of the functions? Then it would become an issue, I imagine.
I am admittedly naive when it comes to just about anything cpp-related, but I feel like it isn't very efficient to include some 750kB of code when probably 90% of it isn't used. It could be that the iequals function uses all of that 750kB, I have no idea.
Then again, if the iequals function includes many of the same libraries, the file would still be just as large.
Thoughts?
Thanks in advance for any advice.
EDIT:
Thanks for the responses. I am doing my best to understand them.
I am a chemical engineer who is rewriting a bunch of horribly slow and poorly optimized VBA macros into a C++ DLL. So far the results have been outstanding and everything functions correctly. I just don't see the need for the extra file size if I only need to do a single type of comparison between two strings.
An example of the comparison I need to do is as follows:
if (SomeBSTR == "SomeTextHere") {
// do stuff
}
or more exactly:
if (Gas == "Methane" or
Gas == "CH4" or
Gas == "C1") return 1;
if (Gas == "Ethane" or
Gas == "C2H6" or
Gas == "C2") return 2;
If this is the ONLY type of comparison that I have to do, can I do it in a more simple way than:
int wStrCmp(const BSTR Str1, const wstring Str2) {
wstring wStr1(Str1, SysStringLen(Str1));
return boost::iequals(Str1, Str2);
}
which is called via:
if (wStrCmp(Gas, L"Methane") or
wStrCmp(Gas, L"CH4") or
wStrCmp(Gas, L"C1")) return 1;
Those last 2 blocks are practically pasted from my code.
Thanks again, guys.
believe me you already just include boost::algorithm::iequals but it use boost::range and std::locale that possibly you don't use them in other places of your code, so this make your code a lot bigger, so I guess for your case there is no other way to do that unless you use some non-standard function like stricmp or strcasecmp.
If you want to compare wide strings on Windows(for example BSTR) you can use _wcsicmp from CRT or lstrcmpiW from Windows runtime(declared in Kernel32.lib that possibly you already linked with it).
I have some logic in a C++ program that is not only insanely complex, it requires multiple solutions for which Prolog is ideal. It's sort of like a firewall config script, checking input for actions, but sometimes more that one action is required.
What I want is something like this:
class PrologEngine
{
LoadLogic(const char* filename) throw PrologException; // Load a file of prolog rules, predicates facts etc in textual format. Must be callable multiple times to load AND COMPILE (for speed) prolog rule files.
std::vector<std::string> Evaluate(const char* predicate_in_string_form = "execute(input, Result)") throw PrologException; Returns a vector of matching predicates in text form.
};
It needs no ability to call back into C++.
AMI Prolog seems to get it, but it's not available on Linux. I'm trying to use SWI-Prolog and can only find 2 examples and and incredibly byzantine API (my opinion)
Can anyone point me to an example that is close to what I'm looking for?
There is A C++ interface to SWI-Prolog, that's high level.
I'm fighting with it, here an example of bridging to OpenGL:
PREDICATE(glEvalCoord1d, 1) {
double u = A1;
glEvalCoord1d( u );
return TRUE;
}
This clean code hides many 'bizantinism', using implicit type conversion and some macro. The interface is well tought and bidirectional: to call Prolog from C++ there are PlCall ('run' a query, similar to Evaluate you expose in the answer) or a more structured PlQuery, for multiple results...
If you don't need to link to openGl, or can wait to ear about the answer that hopefully I'll get from SWI-Prolog mailing list, you should evaluate it.
If you don't mind rewriting the prolog code for use in a native c++ header only library, I'd look into the castor library:
http://www.mpprogramming.com/cpp/
Is there a way out to call a function directly from the what the user inputs ?
For example : If the user inputs greet the function named greet is called.
I don't want any cases or comparison for the call to generate.
#include <iostream>
#include<string>
using namespace std;
void nameOfTheFunction(); // prototype
int main() {
string nameOfTheFunction;
getline(cin,nameOfTheFunction); // enter the name of Function
string newString = nameOfTheFunction + "()"; // !!!
cout << newString;
// now call the function nameOfTheFunction
}
void nameOfTheFunction() {
cout << "hello";
}
And is there a concept of generating the function at run time ?
You mean run time function generation ??
NO.
But you can use a map if you already know which all strings a user might give as input (i.e you are limiting the inputs).
For the above you can probably use std::map < std::string, boost::function <... > >
Check boost::function HERE
In short, no this isn't possible. Names in C++ get turned into memory offsets (addresses), and then the names are discarded**. At runtime C++ has no knowledge of the function or method names it's actually running.
** If debug symbols are compiled in, then the symbols are there, but impractical to get access to.
Generating a function at runtime has a lot of drawbacks (if it is possible at all) and there is generally no good reason to do it in a language like C++. You should leave that to scripting languages (like Perl or Python), many offer a eval() function that can interpret a string like script code and execute it.
If you really, really need to do have something like eval() in a compiled language such as C++, you have a few options:
Define your own scripting language and write a parser/interpreter for it (lots of work)
Define a very simple imperative or math language that can be easily parsed and evaluated using well-known design patterns (like Interpreter)
Use an existing scripting language that can be easily integrated into your code through a library (example: Lua)
Stuff the strings of code you want to execute at runtime through an external interpreter or compiler and execute them through the operating system or load them into your program using dlopen/LoadLibrary/etc.
(3.) is probably the easiest and best approach. If you want to keep external dependencies to a minimum or if you need direct access to functionality and state inside your main program, I suggest you should go for (2.) Note that you can have callbacks into your own code in that case, so calling native functions from the script is not a problem. See here for a tutorial
If you can opt for a language like Java or C#, there's also the option to use the compiler built into the runtime itself. Have a look here for how to do this in Java
I'm using boost filesystem to replace windows C++ functions like CopyFile and MoveFile to get some kind of portability between windows and linux. I'm using copy_file but I have not been able to find anything that moves files like a 'move_file' function. Do boost have a move file function?
I would very much prefer to use boost, but alternative suggestions are welcome.
It's called rename, see the manual. Like the corresponding OS functions, this might or might not work if the source and destination paths are on different file systems. If it doesn't work, use a copy operation followed by a delete operation.
void add_time(ptime& gen_time, int seconds) {
boost::posix_time::millisec_posix_time_system_config::time_duration_type time_elapse(0, 0, seconds);
//time_elapse = p2 - p1;
gen_time = gen_time + time_elapse;
}