2013-03-06 66 views
0

我在線下載了一個軟件包。假設該軟件包名爲aPackage.zip。解壓縮文件夾後,它包含一個可執行文件Cassie.exe,它需要2個輸入文件file1.txt和file2.txt。我只需要雙擊Cassie.exe就會自動開始運行。現在我想測量運行Cassie.exe需要多少時間,因此我用Visual C++ 2010 express編寫了一個新項目(TimeMeasure)的小型C++程序(main.cpp)。但是,雖然我將Cassie.exe,file1.txt和file2.txt放在同一個文件夾內,但Cassie.exe仍然不斷抱怨無法打開file2.txt。以下是TimeMeasure項目的main.cpp代碼。無法從C++程序調用可執行文件

#include <iostream> 
#include <fstream> 
#include <stdlib.h> 
#include <stdio.h>  /* printf */ 
#include <time.h>  /* clock_t, clock, CLOCKS_PER_SEC */ 
#include <math.h>  /* sqrt */ 

using namespace std; 

int main() { 

    const clock_t begin_time = clock(); 
    system("C:\\aPackage\\Cassie.exe C:\\aPackage\\file1.txt C:\\aPackage\\file2.txt"); 

    ofstream myfile; 
    myfile.open ("Time.txt"); 
    myfile << "Time used is %d sec \n"<<float(clock() - begin_time)/CLOCKS_PER_SEC; 
    myfile.close(); 
    system("PAUSE"); 
    return 0; 
} 

的TimeMeasure項目在路徑

C:\Users\Cassie\Documents\Visual Studio 2010\Projects\TimeMeasure 

創建這就是爲什麼我使用絕對路徑aPackage文件夾。我的電腦是Windows 7家庭操作系統。誰能告訴我我做錯了什麼?非常感謝,

+0

不是你的_specific_問題的答案,但http://stackoverflow.com/questions/673523/how-to-measure-execution-time-of-command-in-windows-command-line – paxdiablo 2013-03-06 08:05:37

+1

如果你'cd '進入你的項目目錄,然後輸入'C:\ aPackage \ Cassie c:\ aPackage \ file1.txt c:\ aPackage \ file2.txt' - 會發生什麼?如果它不起作用,那麼可能是因爲cassie在嘗試打開它們之前對這些參數做了某些操作,例如在當前工作目錄中加上前綴。首先將'chdir()'改爲'c:\ aPackage'可能最簡單。如果你真的想確認發生了什麼,你可以看到一個程序向你展示cassie嘗試的'open()'系統調用 - 在UNIX上它會是'strace',在Windows上可能是sysinternals實用程序之一。 – 2013-03-06 08:09:11

+0

我不使用Windows,但是孩子可以繼承調用者的環境,而不是自己設置。 – corazza 2013-03-06 08:09:20

回答

0

Cassie.exe可能會查找當前目錄中的兩個文件。當您雙擊一個可執行文件來運行它時,當前目錄被設置爲與可執行文件所在的目錄相同的目錄,因此它可以工作。當您使用system()時,當前目錄不變(在這種情況下,包含TimeMeasure的目錄),所以它不起作用。

使用_chdir調用system之前設定的當前目錄,或嘗試像

system("cd /d C:\\aPackage && Cassie.exe"); 

應該幾乎完全一樣雙擊的效果相同。

相關問題