54

What I want to do is open an .exe from another .exe. I really don't know how to do this, so I searched the internet. I tried some suggested methods from the internet, but it didn't work.

Here's my code:

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    system ("OpenFile.exe");
    system ("pause");
    return 0;
}

When I run it in DEV C++, it compiles, but I get a error. Can someone please help me?

Lucas
  • 17,277
  • 5
  • 45
  • 40
S.Y
  • 689
  • 2
  • 10
  • 12
  • 3
    What is the error? In any event, on a hunch, [man system](http://linux.die.net/man/3/system) - try `#include ` – RageD Mar 15 '13 at 15:20
  • 12
    You could try `fopen()`. It'll open your .exe. – Kerrek SB Mar 15 '13 at 15:24
  • RageD, thank for that it compiled but the program is still not opening openfile.exe – S.Y Mar 15 '13 at 15:26
  • 1
    @KerrekSB I'm pretty sure the OP is trying to *execute* the file, not actually read its contents. In which case, `system` would be the right way to go. I'm pretty sure @RageD gave the right answer with the missing `#inlcude `. – JSQuareD Mar 15 '13 at 15:26
  • @S.Y Are you sure the file is in the right place? That is, in the same location as the executable of your program? Try running outside of Dev-C++, it may do some obscure things with your execution path. – JSQuareD Mar 15 '13 at 15:28
  • @JSQuareD its all on my desktop the program open i just get a blinker waiting from text input – S.Y Mar 15 '13 at 15:30
  • @S.Y What kind of program is `OpenFile.exe`? If it's another console application, you might be interacting with that program; It could be that it's actually `OpenFile.exe` that's 'waiting for text input'... – JSQuareD Mar 15 '13 at 15:36
  • @JSQuareD at the top of the console it tell me what exe it is anyway i have text that come up on the program before it ask from input – S.Y Mar 15 '13 at 15:40
  • @S.Y You should accept the answer that worked for you, and I think Jona's reply should do it in your case – SAAD Oct 07 '15 at 08:21

7 Answers7

98

You should always avoid using system() because

  • It is resource heavy
  • It defeats security -- you don't know you it's a valid command or does the same thing on every system, you could even start up programs you didn't intend to start up. The danger is that when you directly execute a program, it gets the same privileges as your program -- meaning that if, for example, you are running as system administrator then the malicious program you just inadvertently executed is also running as system administrator. If that doesn't scare you silly, check your pulse.
  • Anti virus programs hate it, your program could get flagged as a virus.

You should use CreateProcess().

You can use Createprocess() to just start up an .exe and creating a new process for it. The application will run independent from the calling application.

Here's an example I used in one of my projects:

#include <windows.h>

VOID startup(LPCTSTR lpApplicationName)
{
   // additional information
   STARTUPINFO si;     
   PROCESS_INFORMATION pi;

   // set the size of the structures
   ZeroMemory( &si, sizeof(si) );
   si.cb = sizeof(si);
   ZeroMemory( &pi, sizeof(pi) );

  // start the program up
  CreateProcess( lpApplicationName,   // the path
    argv[1],        // Command line
    NULL,           // Process handle not inheritable
    NULL,           // Thread handle not inheritable
    FALSE,          // Set handle inheritance to FALSE
    0,              // No creation flags
    NULL,           // Use parent's environment block
    NULL,           // Use parent's starting directory 
    &si,            // Pointer to STARTUPINFO structure
    &pi             // Pointer to PROCESS_INFORMATION structure (removed extra parentheses)
    );
    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}

EDIT: The error you are getting is because you need to specify the path of the .exe file not just the name. Openfile.exe probably doesn't exist.

iBug
  • 35,554
  • 7
  • 89
  • 134
Jona
  • 1,747
  • 2
  • 16
  • 22
  • There is a good example in https://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v=vs.85).aspx (at the end of the link in this answer, but easy to miss). And a little tip, if someone is using `lpApplicationName` with a exe-path that includes spaces, it should **not** be surrounded with `"`, only if both exe and command line is in argv[1]. – 244an Mar 24 '17 at 22:09
  • 4
    I think you must change the function from void to bool, and to return true/false based on the success of CreateProcess() – Michael Haephrati Sep 09 '17 at 17:57
  • Does CreateProcess launch a program as a background process (potentially keeping it open after it has finished executing)? – user8951490 Feb 08 '18 at 15:15
  • 1
    I'm not sure I understand why you've put argv[1] as the second parameter of CreateProcess. – aj.toulan Sep 27 '19 at 20:49
  • 3
    Same here. It's confusing. @iBug can you clarify char argv[1] actually is? I assume command line parameters? – Digital Human Mar 18 '20 at 14:20
  • @Jona how can I do the same in Ubuntu? – Ali Rojas Nov 19 '20 at 05:55
  • you better show how to invoke this function because now i am confused about LPCTSTR and string parameter. – Azzurro94 Mar 23 '21 at 00:36
  • If you want to be compatible with `WinExec` which accepts exe and arguments in a variable. Put the commandline in second argument and make first argument `NULL` – Louis Go Mar 25 '22 at 03:42
26

I've had great success with this:

#include <iostream>
#include <windows.h>

int main() {
    ShellExecute(NULL, "open", "path\\to\\file.exe", NULL, NULL, SW_SHOWDEFAULT);
}

If you're interested, the full documentation is here:

http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx.

d7samurai
  • 3,086
  • 2
  • 30
  • 43
Morpheus13
  • 369
  • 4
  • 3
  • CreateProcess() is better than ShellExecute() – Michael Haephrati Sep 09 '17 at 17:59
  • 2
    @Michael Thats a personal opinion - whats the validation? I think the opposite is true for a number of reasons: 1. ShellExecute is an OS function and can be properly protected. 2. ShellExecute is certainly more simplistic and will probably not change too much over time. CreateProcess - you should be using CreateProcessEx to be 'proper'. 3. There are many ambiguities about the use of CreateProcess, and for new users the security and flag settings are non-obvious. Im actually not sure what specific benefit CreateProcess does have? Please explain your rationale. – David Lannan Nov 08 '18 at 04:50
  • 1
    CreateProcess is also an OS function. See https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createprocessa. If you review software projects, I think you will find that CreateProcess is used in the more professional ones I guess because of your control over: LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, and also bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo and lpProcessInformation – Michael Haephrati Nov 08 '18 at 10:54
  • 1
    @DavidLannan, just had an opportunity to realize why CreateProcess is advanced over ShellExecuteEx and wanted to share that with you. If you wish to run a CMD command and wait for the command to be completed, the best way is to use CreateProcess() and then check the completion of the execution using these lines of code: WaitForSingleObject(ShExecInfo.hProcess, INFINITE); DWORD exitCode = 0; if (GetExitCodeProcess(ShExecInfo.hProcess, &exitCode) && exitCode != STILL_ACTIVE) { } – Michael Haephrati Nov 13 '18 at 00:31
7

Try this:

#include <windows.h>

int main ()

{
    system ("start notepad.exe") // As an example. Change [notepad] to any executable file //

    return 0 ;
}
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
ILys Hdm
  • 113
  • 1
  • 1
  • 5
    Could you please [edit] in an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/q/148272/274165), because they don't teach the solution. – Nathan Tuggy Jul 16 '15 at 02:58
  • What's the difference between what you did here and what S.Y did? –  Jul 02 '16 at 23:08
  • this is the better solution imo – Charlie Apr 18 '18 at 20:26
  • 1
    `system`'s syntax can be a little confusing if you have spaces in your path. It took me a while to craft this `system("cmd /C \"\"C:\\Program Files (x86)\\My Cool App\\My Cool App.exe\"\"");`. I based it off this answer https://stackoverflow.com/questions/9964865/c-system-not-working-when-there-are-spaces-in-two-different-parameters – user875234 Oct 05 '18 at 12:41
1

When executable path has whitespace in system, call

#include<iostream>
using namespace std;
int main()
{
    system("explorer C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe ");
    system("pause");
return 0;
}
CHE98
  • 31
  • 1
1

Provide the full path of the file openfile.exe and remember not to put forward slash / in the path such as c:/users/username/etc.... instead of that use c:\\Users\\username\etc (for windows)

May be this will help you.

0

You are getting this error because you are not giving full path. (C:\Users...\file.exe) If you want to remove this error then either give full path or copy that application (you want to open) to the folder where your project(.exe) is present/saved.

#include <windows.h>
using namespace std;
int main()
{
  system ("start C:\\Users\\Folder\\chrome.exe https://www.stackoverflow.com"); //for opening stackoverflow through google chrome , if chorme.exe is in that folder..
  return 0;
}
udit043
  • 1,610
  • 3
  • 22
  • 40
0

I know this is a bit late but this is to help all the new the c++ devs.

Basically I found that if you set the file path to the location then call the program you can bypass the error.

        cout << "Opening Firefox";
        system("cd C:\\Program Files\\Mozilla Firefox");
        Sleep(1000);
        system("start firefox.exe -P");

As you can see I set the file path to the location of Firefox then launch it. In my case I'm launching the Profile manager of Firefox, if you want to launch just Firefox remove the -P. I also put in a Sleep() to give my computer time to switch file paths. if you want to go back to the default file path use, system(cd C:\\Windows\\System32);. I made this by replicating commands in the command line for windows, though you would use Linux specific commands + file paths if that is what you are using.