开发者

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"); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜