Blocking the standard error output of a programmatically run system command
-
19-08-2019 - |
Question
I have this program in c++:
#include <iostream>
using namespace std;
int main()
{
char buf[50];
cin.getline(buf,49);
system(buf);
return 0;
}
When I run and compile it and type for example "helo", my program prints the error:
"helo" not found.
Can I stop this error from being displayed? Is there any way to disable the error from the system command?
Solution
You can't change the way system
displays errors. C and C++ put very little to no requirements on implementations in that regard, so that large parts of it are left unspecified, to allow them to be as flexible as possible.
If you want more precise control, you should use the functions of your runtime library or operation system interface. Try execvp
(see man execvp
) in linux/unix or the CreateProcess function for windows systems, which uses the Windows API that allows great control over error handling and other stuff.
OTHER TIPS
Are you on linux? Try typing "./hello"
If this works, the reason is that the current directory (".") is not in the search path. You must indicate that the compiled program is "there" in the directory.
Alternatively, you can do something like
export PATH=$PATH:.
This adds "." (current directory) to the search path.
If you are on windows, try "hello.exe"
If you're on Linux, can you try redirecting the error output to the null
device?
strcat(buf, "2> /dev/null");
system(buf);