2016-07-25 46 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();

相关问题