2016-07-25 45 views
0

我需要執行多次FORTRAN程序,這需要用戶每次插入4個數字值。 我發現了一個解決方案,使用Python腳本自動完成此操作......此腳本基本上在每次迭代時創建一個包含以下行的.sh文件(a.out是我必須自動執行的FORTRAN程序的名稱)C++系統()導致「文本文件忙」錯誤

./a.out<<EOF 
param01 
param02 
param03 
param04 
EOF 

使其可執行,並執行它。

所以,我試圖做的在C++一樣......我寫的東西像

int main() 
{ 

long double mass[3] = {1.e+10,3.16e+10,1.0e+11}; 
double tau[3] = {0.5,0.424,0.4}; 
double nu[3] = {03.0,4.682,10.0}; 
long double Reff[3] = {1.0e+3,1.481e+3,3.0e+3}; 
int temp=0; 



for (int i=0; i<3; i++) 
    { 
    ofstream outfile("shcommand.sh"); 
    outfile << "./a.out<<EOF" << endl << mass[i] << endl << nu[i] << endl << Reff[i] << endl << tau[i] << endl << "EOF" << endl; 
    temp=system("chmod +x shcommand.sh"); 
    temp=system("./shcommand.sh"); 
    } 

return 0; 

} 

但是當我跑我的C++程序,我收到以下錯誤消息

sh: 1: ./shcommand.sh: Text file busy 
sh: 1: ./shcommand.sh: Text file busy 
sh: 1: ./shcommand.sh: Text file busy 

在上一次迭代完成之前,是否與嘗試修改.sh文件的C++程序有關? 我在網上看,我似乎明白了命令完成後,系統()命令onlyreturns ...

+0

爲什麼你從來不使用'system'的結果?你沒有錯誤檢查。 –

+2

在嘗試運行之前是否關閉了該文件? (例如outfile.close()) – swdev

回答

3

您正試圖運行一個打開的文件,這不是一個好主意。前chmod鼎關閉/運行它:

for (int i=0; i<3; i++) 
{ 
    { 
     ofstream outfile("shcommand.sh"); 
     outfile << "./a.out<<EOF" << endl << mass[i] << endl << nu[i] << endl << Reff[i] << endl << tau[i] << endl << "EOF" << endl; 
     // the file is closed when outfile goes out of scope 
    } 
    temp=system("chmod +x shcommand.sh"); 
    temp=system("./shcommand.sh"); 
} 

順便說一下,就可以避免這一切殼爛攤子通過直寫你的計劃(popen EG)的標準輸入:

for (int i=0; i<3; ++i) { 
    FILE *fd = popen("./a.out", "w"); 
    assert(fd!=NULL); // do proper error handling... 
    fprintf(fd, "%Lf\n%f\n%Lf\n%f\n", mass[i], nu[i], Reff[i], tau[i]); 
    fclose(fd); 
} 
2

這似乎是因爲shell仍然無法讀取腳本,因爲它仍然是由您的程序打開。

在致電system()之前,嘗試添加outfile.close();

相關問題