viewing output of system() call in C++ - c++

How can I view the output of a system command. Ex:
int _tmain(int argc, _TCHAR* argv[]) {
system("set PATH=%PATH%;C:/Program Files (x86)/myFolder/bin");
system("cd C:/thisfolder/");
std::cin.get();
return 0;
}
when I run the program in Visual Studio it give me a black screen and I cannot see the command being run. I need it so I can view whether it worked or not. Thanks!

Use popen instead of system. See example here https://msdn.microsoft.com/en-us/library/96ayss4b.aspx
char psBuffer[128];
FILE *pPipe;
if( (pPipe = _popen( "set PATH=%PATH%;C:/Program Files (x86)/myFolder/bin", "rt" )) == NULL )
exit( 1 );
then
while(fgets(psBuffer, 128, pPipe)) {
printf(psBuffer);
}
if (feof( pPipe))
printf( "\nProcess returned %d\n", _pclose( pPipe ) );

The output of a system call should show up on stdout.
I do not think those commands generally have any output to display if they are successful. Try adding a dir or pwd after to list the directory you are in.
If you want to get the output from the commands into the program for processing that is another issue. You will have to use os specific api, or maybe redirect the output into a file you can read.

Try adding pause as below to wait after each command. On failure, error message will be displayed. On success, actual output from the command, if any, will be displayed.
system("set PATH=%PATH%;C:/Program Files (x86)/myFolder/bin & pause");
system("cd C:/thisfolder/ & pause");
Note that each call to system uses cmd.exe( as cmd /c [command] ) to execute your command and env variables like PATH in one command won't effect another.
cmd.exe /c set PATH=%PATH%;C:/Program Files (x86)/myFolder/bin
cmd.exe /c cd C:/thisfolder/

Related

_popen fails to return java version

In my C++ on Windows program I have to collect java version by firing the command "java -version".
I am using _popen API for the same.
When I use _popen command for firing any windows command prompt commands then _open returns properly the output of the command in the buffer.
char versionCmd[256] = "";
char buffer[1024];
strcpy(versionCmd, "netstat -an");
FILE *File_p = _popen(versionCmd, "r");
if (!File_p)
{
return -1;
}
while(fgets(buffer, sizeof(buffer), File_p))
{
printf("buffer = %s", buffer);
}
But when I run the same program with command "java -version" then _popen does not return anything in the buffer.
strcpy(versionCmd, "java -version");
Instead the output gets printed on the console from where I ran this windows program.
Looks like the output of the command is getting redirected to console instead of buffer.
Is there anyway I can redirect the output of the "java -version" command to the program's buffer?
How to resolve this issue?

Creating a command prompt process that opens at a chosen directory

Need help here, I'm trying to create a process in c++ with the windows api, whats happening is the process is being created which is cmd.exe however I want cmd.exe to open cd'd at a certain directory i.e. root c:\, however the process is opened at the dir of the executable.
I tried passing in "cd \" as the second argument of the CreateProcess function to no avail
Here's a snippet of the code:
TCHAR program[] = TEXT("C:/Windows/System32/cmd.exe");
TCHAR command[] = TEXT("cd /");
STARTUPINFO info;
PROCESS_INFORMATION processInfo;
ZeroMemory(&info,sizeof(STARTUPINFO));
ZeroMemory(&processInfo,sizeof(PROCESS_INFORMATION));
BOOL processResult =
CreateProcess(program,
command, NULL, NULL,
TRUE, CREATE_NEW_CONSOLE,
NULL, NULL,
&info,
&processInfo);
if(!processResult){
std::cerr << "CreateProcess() failed to start program \""
<< program << "\"\n";
exit(1);
}
std::cout << "Started program \""
<< program << "\" successfully\n";
Help would be extremely appreciated!
Thanks
If you want the cd / (or any other command) to have any effect, you need to use either the /k or /c flags for the command prompt. You can look these switches up in the documentation for cmd.exe, but basically, /c runs the command and then terminates, while /k runs the command and keeps the console session open. You almost certainly want /k here.
But really, you should be specifying the directory as the working directory for the process, not executing a change-directory command.
You can do this easily by calling the ShellExecute function, as Raw N suggested. The working directory is one of its parameters. ShellExecute (or ShellExecuteEx) is easier to use than CreateProcess, and should be preferred unless you need some special low-level behavior that you can only get with CreateProcess.
This works with CreateProcess too: pass the path as the lpCurrentDirectory parameter.
Whatever you do, don't hard-code paths! Use the %comspec% environment variable on Windows NT. It would also work to just execute cmd, letting the default search paths do their job.

Console prompt window appear on system("start dir") but not on system("start ipconfig")

I try to create a simple UI which runs a command prompt in the background (but the windows console must not disappear) while clicking on each button, resp.
But before, I try something like system("start dir"); to see if the button works.
Here is the problem: when I click on the left button the windows console appear and don't exit unit I close it. But this only work with system("start dir");. If I change dir to ipconfig (or another call-function) the windows console will appear for a second and the exit. I tried something like system("PAUSE"); or getch(); etc, but it doesn't work.
Why does this command work with dir but not with another command?
There is a fundamental difference between DIR and IPCONFIG, the DIR command is built into the command processor (aka shell), IPCONFIG is a separate program stored in c:\windows\system32.
When you type START /? at the command line then you can see why it treats them differently:
If it is an internal cmd command or a batch file then
the command processor is run with the /K switch to cmd.exe.
This means that the window will remain after the command
has been run.
If it is not an internal cmd command or batch file then
it is a program and will run as either a windowed application
or a console application.
The alternative is to ask the command processor to execute the command and exit afterwards. You do with the /c option:
system("cmd.exe /c dir");
Or simpler yet, since system() automatically passes off the job to the command processor:
system("dir");
Just stop using start :)

Nodejs and UNIX newbie: run node command in a cpp program

I'd like to run a nodejs program through the system() function in stdlib.h. I can run the bash command /usr/local/bin/node ~/some_folder/xml2js.js in terminal, but when I ran this:
int main(int argc, const char * argv[])
{
// insert code here...
//system("/usr/local/bin/node ~/some_folder/xml2js.js");
system("~/some_folder/run.sh");
std::cout << "Hello, World!\n";
return 0;
}
It told me node: command not found.
the run.sh is below:
#! /bin/bash
node ./xml2js.js
Are there any other ways to call other programs in UNIX? And how to get the output of the command into stdout?
Try writing the absolute path to that script. It should work.
You could try system("/home/$(whoami)/some_folder/run.sh") assuming that your user's home folder is in /home.
Also, does that script have execute permissions? Also, check the return code of system.

call an exe from within c++ (windows)

I'm using VS2010 and I would like to call an exe file which I've created in another directory.
I've tried the following:
int main(){
system("C:\\Users\\Li\\Desktop\\Debug\\modelExample_4pcs.exe");
return 0;
};
but I get "The system could not find the file specified" error.
I've tried to run the exe file directly from the command line, and it only works when I'm inside its directory.
Could you please tell me how can I run it from a different directory?
(I'm using win7)
Thanks,
Li.
You should try using CreateProcess Windows API funcion: http://msdn.microsoft.com/en-us/library/ms682425%28VS.85%29.aspx
Try opening the file for reading, just to check that you have the path right:
char* filename = "C:\\Users\\Li\\Desktop\\Debug\\modelExample_4pcs.exe" ;
FILE* fp = fopen (filename, "rb") ; // Open for reading, binayr mode
if (fp == 0) {
printf ("Duh! File not found\n") ;
exit (0) ;
}
printf ("File found\n") ;
fclose (fp) ;
// Now try the system call, as before:
system(filename);
What happens?
You should be able to use ShellExecute like so: (adjusting the params sent to ShellExecute for your situation) http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx?ppud=4
HINSTANCE hinst = ShellExecute( NULL, _T("open"), commandLine.c_str(), additionalParams.c_str(), NULL, SW_RESTORE );
if(hinst <= (HINSTANCE)SHELLEXERROR)// see: http://msdn2.microsoft.com/en-us/library/bb762153.aspx for further info on the return values
Now given that you are using Win7, you may be having a privilege issue and you need to run at an elevated level (i.e. administrator) you can test this by opening cmd as admin and running your exe from another directory
and as Steve mentioned above you can certainly use CreateProcess.
HTH,
EB
System() may not be able to find cmd.exe to open your environment.
Try using cmd.exe to execute your app via the /C option.
System("C:\\WINDOWS\\system32\cmd.exe /C \"C:\\Users\\Li\\Desktop\\Debug\\modelExample_4pcs.exe\"");
Try this using CreateProcess. Less (or at least different) environmental dependencies than using system(). At least you will get a nice Win32 error code if this still fails.
http://msdn.microsoft.com/en-us/library/ms682425(VS.85).aspx
Check your path, and make sure you escape all characters: C:\\Users\Li..
Is the error from running the main program, not from launching modelExample_4pcs.exe? Try commenting out the system() call and see if you get the same error.
Your main program is not on the path when you're outside its folder...
Is modelExample_4pcs.exe trying to load another file from the current working folder, and THAT's what's generating the error?
Maybe try chdir() before the call to system().
Just change to the directory first, like you would do from the command prompt:
system("C: && CD \\Users\\Li\\Desktop\\Debug\\ && modelExample_4pcs.exe");