Is there a way to get a C stream object (a FILE* object) that points at nothing?
I know fopen("/dev/null","w"); would work but I'm wondering if there is a better way.
Preferably that bit buckets the data at a higher level than the posix layer and that is also more portable.
No: /dev/null on Unix and NUL: on Windows (in the absence of Cygwin or equivalent) is the best way to do it.
(The original version of the question mentioned fopen("/dev/null","o"); but has since been fixed.)
Oh, and the "o" flag to fopen() is non-portable. The portable forms include flag characters r, w, a, b, + in various combinations.
I have some logging in place that goes to stderr and I want to be able to turn it off with a flag. I'd really rather not have to do more to it than change the variable that gets passed to fprintf
a) Wrapper function
logging = TRUE;
void debugprint(...)
{
if (logging)
{
fprintf(stderr, ...);
}
}
b) I think fprintf will return if you give it a null pointer. Can't remember -- give it a try. Then all you have to do is change the pointer :)
Related
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.
I need to write to anonymous pipe something like double (*fun)(double), but the following WriteFile(pipe, fun, 4, written_bytes, 0) causes an error in a pipe-receiver while ReadFile(read_pipe, fun, 4, written_bytes, 0). Are there any methods to do this?
I have an idea. I can create a struct with field of same type:
struct Foo
{
double (*f)(double);
};
And then I write it WriteFile(hWritePipe_StdIN, &to_process, sizeof(Foo), &bytes, 0);
But I have problem, that pipe-receiver never ends to read data:
ReadFile(hReadPipe, &to_process, sizeof(Foo), &bytes, 0);
There are some problems with it:
First, you should know the size of function.
If you do, you just call WriteFile(pipe, funcPtr, funcSize, ...) to transfer it.
Second, the function should contain only position-independent code, and don't address any data.
E.g. a function like this won't work:
double fun(double x)
{
int arr[10000]; // implicit function call (alloca or something like this)
printf("some");
static int some = 1;
return globalVal + (++some);
}
because function printf will have a different address and there will be no static variable and string in another process.
(Well, maybe you can transfer data as well, but there is no way you'll generate PI code.)
So, with all that limitations, you can send a function:
__declspec(naked) double fun(double x) { __asm ret }
const auto funcSize = 1;
WriteFile(pipe, &fun, funcSize, ...);
In native code you can not send function (the code) itself, neither to the same nor to different process. (You could try low-level hacking like the one #Abyx suggests, but it seriously limits functionality that the code can perform, and will probably make you resort to writing it all in assembler by hand.)
You also can't send function's address to another process, because each process has its own isolated address space; in another process, that address will contain different data.
The solution will be to create a shared library (preferably dynamic) that will contain all functions that could possibly be sent this way. Assign each function some tag (e.g. number or name), let DLL maintain a mapping between tags and addresses. Then send tags instead.
What are you trying to achieve, here? Are you really trying to write the function itself? Why? That's not something you can easily do in C++, for instance because the size of a function is not well-defined.
You should probably write the data, i.e. the number returned by fun() instead:
const double value = fun(input);
DWORD numberOfBytesWritten;
WriteFile(pipe, &value, sizeof value, &numberOfBytesWritten, NULL);
You should of course add code to check the output. Note that writing binary data like this can be brittle.
Since you're using WinAPI, the native way to send a function is via COM. In particular, expose the function as a method on a COM object, obtain a COM moniker, and send the moniker. Monikers can be serialized and sent over pipes. The other side can deserialize the moniker and get access to your object.
Under water, this works by looking up the object in the COM Running Object Table
Seeing how this is excessively complicated and error-prone to do in C++ (and only works with a very limited set of functions at all), I recommend you use a scripting language for this. Instruction caches and DEP are another two things you'd have to consider in addition to the already mentioned ones.
Really. Transmit the function as script, and run it on the other end. Save yourself that pain.
Angelscript looks and feels almost like C++, so that might be a possible candidate.
Now, if you object to this because you need something that a script cannot trivially do, knoweth: C++ will not be able to do it either, in this scenario.
Apart from the above mentioned PIC code issue (#Abyx) and the fact that you cannot safely or portably know a function's size, the only C++ functions that you could conceivably send via a pipe and execute in a meaningful manner are strictly const functions. Here, const is in the sense of e.g. GCC's __attribute__((const)), not the C++ const keyword.
That is, any such function may not examine any values except its arguments, and have no effects except the return value. The reason is obvious: A different process lives in a different address space, so anything you reference is meaningless. Anything you change is meaningless.
Now, this is just what a script can do, in a safe, straightforward manner, and reliably. The overhead is, considering you already send code through a pipe, neglegible.
In my C++-code there are several fprintf-statements, which I have used for debugging. Since I might need them again, I would prefer not to comment them out for the moment.
However, I need the execution of the program to be fast, so I would like to avoid them being printed out, as they are for the moment (I redirected stderr to a file).
Preferably this would be determined by the user passing an argument to the program, which I would extract like this:
main (int argc, char *argv[])
{
int isPrint=0;
if (argc > 1 ) {
isPrint = atoi ( argv[2]);
}
}
I thought of renaming fprintf to another name, and then from that function do a fprintf-call using the same parameters, based on the value of isPrint; however, then I realized that fprintf can have so many different kind of arguments and a various number of arguments; and that I don't know any generic way of declaring my own function with those requirements.
So I wonder how to create a function,which works exactly like fprintf, but which takes the extra parameter isPrint; or how to solve the above problem in another way.
Complementary information after first post:
One solution would be to add this before each fprintf-statement:
if (isPrint == true )
The typical approach is to use the preprocessor to compile away the calls to fprintf().
You would do something like this:
#if defined DEBUG
#define LOG(a) fprintf a
#else
#define LOG(a)
#endif
And in the code you would do:
LOG(("The value is %f", some_variable));
Note the double parenthesis, that's just to make the syntax work. You can do it nicer, but this is simpler to explain.
Now, you would either just edit the code to #define or #undef the DEBUG preprocessor symbol at the top of the file, or pass suitable options to the compiler (-D for GCC).
First note that if this is just for debugging, I'd agree that the typical way is to use macros or preprocessor defines to tell the compiler to include logging or not.
However, if you don't want it removed entirely by the compiler (so that you can turn the printing on or off with an argument), you could write your own log function that takes isPrint and some string, and then use snprintf() to format the string before you call it.
Something along these lines:
void myLog(int isPrint, char *message)
{
if(isPrint == 1)
{
fprintf(logFile, "%s", message);
}
}
char msg[64];
snprintf(msg, 64, "Test Message %d", 10);
myLog(isPrint, msg);
It may also be possible to wrap fprintf() in your own varags function, but that would be more complicated.
For debugging purpose you can use the variable argument macro:
#ifdef DEBUG
#define FPRINTF(...) fprintf(__VA_ARGS__)
#else
#define FPRINTF(...)
#endif
Be attentive that, if you use fprintf directly instead of FPRINTF then since you are defining a library function, it should appear after #include<> of that function.
It depends how much flexibilty you've got in changing the code and whether you want to be able to switch this off at runtime or just compile time.
I'd suggest you wrap it in your own variadic function (for tips look here) and then you've encapsulated the functionality.
Your function will essentially be just a thin wrapper round fprintf() but at this point you can then either use the preprocessor to ensure that your logging function does nothing if you compile it out, or you can do an integer comparison with, say, a logging level at runtime so that the underlying fprintf() only gets called if your debugging level is high enough.
At some places in my code, I print debug messages like this:
int ret = getLinkSpeed(device.getSysName(), linkSpeed);
if (ret < 0)
{
logDebug("Failed to obtain port speed for this device. Error: " + std::string(strerror(errno)));
}
From the documentation it is not entirely clear if strerror will return 0 under certain conditions (which would cause my code to crash). Does anyone know if it's safe?
Why not write a function to do this:
string ErrStr() {
char * e = strerror(errno);
return e ? e : "";
}
This is easy to use, self-documenting, can be adapted to reformat the output and covers the possibility that strerror() might return NULL (I don't know if it can).
Where you might get problems, is if you use a multi-threaded application. In this case, you need to use strerror_r
Good question (+1), the documentation seems quite vague. I'm not sure if there is a "harder" source, such as the POSIX specification for instance.
Thinking a bit pragmatically, here is GNU libc's implementation. It returns a pointer to a static string buffer, so it cannot return 0.
In response to p00ya's comment, the safe (and also very pragmatical, heh) thing to do in the face of conflicting, vague or incomplete specifications is of course to assume the worst, and
not assume that the return value will always be a valid string.
I see C's getcwd via:
man 3 cwd
I suspect C++ has a similar one, that could return me a std::string .
If so, what is it called, and where can I find it's documentation?
Thanks!
Ok, I'm answering even though you already have accepted an answer.
An even better way than to wrap the getcwd call would be to use boost::filesystem, where you get a path object from the current_path() function. The Boost filesystem library allows you to do lots of other useful stuff that you would otherwise need to do a lot of string parsing to do, like checking if files/directories exist, get parent path, make paths complete etcetera. Check it out, it is portable as well - which a lot of the string parsing code one would otherwise use likely won't be.
Update (2016): Filesystem has been published as a technical specification in 2015, based on Boost Filesystem v3. This means that it may be available with your compiler already (for instance Visual Studio 2015). To me it also seems likely that it will become part of a future C++ standard (I would assume C++17, but I am not aware of the current status).
Update (2017): The filesystem library has been merged with ISO C++ in C++17, for
std::filesystem::current_path();
std::string's constructor can safely take a char* as a parameter. Surprisingly there's a windows version too.
Edit: actually it's a little more complicated:
std::string get_working_path()
{
char temp[MAXPATHLEN];
return ( getcwd(temp, sizeof(temp)) ? std::string( temp ) : std::string("") );
}
Memory is no problem -- temp is a stack based buffer, and the std::string constructor does a copy. Probably you could do it in one go, but I don't think the standard would guarantee that.
About memory allocation, via POSIX:
The getcwd() function shall place an absolute pathname of the current working directory in the array pointed to by buf, and return buf. The pathname copied to the array shall contain no components that are symbolic links. The size argument is the size in bytes of the character array pointed to by the buf argument. If buf is a null pointer, the behavior of getcwd() is unspecified.
Let's try and rewrite this simple C call as C++:
std::string get_working_path()
{
char temp [ PATH_MAX ];
if ( getcwd(temp, PATH_MAX) != 0)
return std::string ( temp );
int error = errno;
switch ( error ) {
// EINVAL can't happen - size argument > 0
// PATH_MAX includes the terminating nul,
// so ERANGE should not be returned
case EACCES:
throw std::runtime_error("Access denied");
case ENOMEM:
// I'm not sure whether this can happen or not
throw std::runtime_error("Insufficient storage");
default: {
std::ostringstream str;
str << "Unrecognised error" << error;
throw std::runtime_error(str.str());
}
}
}
The thing is, when wrapping a library function in another function you have to assume that all the functionality should be exposed, because a library does not know what will be calling it. So you have to handle the error cases rather than just swallowing them or hoping they won't happen.
It's usually better to let the client code just call the library function, and deal with the error at that point - the client code probably doesn't care why the error occurred, and so only has to handle the pass/fail case, rather than all the error codes.
You'll need to just write a little wrapper.
std::string getcwd_string( void ) {
char buff[PATH_MAX];
getcwd( buff, PATH_MAX );
std::string cwd( buff );
return cwd;
}
I used getcwd() in C in the following way:
char * cwd;
cwd = (char*) malloc( FILENAME_MAX * sizeof(char) );
getcwd(cwd,FILENAME_MAX);
The header file needed is stdio.h.
When I use C compiler, it works perfect.
If I compile exactly the same code using C++ compiler, it reports the following error message:
identifier "getcwd" is undefined
Then I included unistd.h and compiled with C++ compiler.
This time, everything works.
When I switched back to the C compiler, it still works!
As long as you include both stdio.h and unistd.h, the above code works for C AND C++ compilers.
All C functions are also C++ functions. If you need a std::string, just create one from the char* that getcwd gets for you.
I also used boost::filesystem as stated in another answer above. I just wanted to add that since the current_path() function does not return a std::string, you need to convert it.
Here is what I did:
std::string cwd = boost::filesystem::current_path().generic_string();
You could create a new function, which I would prefer over linking to a library like boost(unless you already are).
std::string getcwd()
{
char* buff;//automatically cleaned when it exits scope
return std::string(getcwd(buff,255));
}