在我的程序的某个时候,我想运行另一个程序(它从stdin获取参数),以及我在文本文件中准备的参数。然后,我想将程序的输出写入另一个文件。在C中执行程序
我是linux,fork等新手。试图打破我的头小时没有成功。 我读到我应该将输入文件与标准输入和输出文件与标准输出关联起来,就像那样。
这是我写的代码:
//move on all sub-directories .....
while((indir=readdir(dir))!=NULL)
{
pid_t pid;
DIR *currDir;
struct dirent *cfile;
char *fullpath, *outpath, *outputpath;
//ignore hidden files
if(indir->d_name[0]=='.')
continue;
//create the full path of c file
fullpath=(char*)calloc(strlen(dirpath)+strlen(indir->d_name)+1,sizeof(char));
strcpy(fullpath,dirpath);
fullpath=strcat(fullpath,indir->d_name);
fullpath=strcat(fullpath,"/");
//open current directory
currDir=opendir(fullpath);
//get the c file, ignore hidden files
while((cfile=readdir(currDir))!=NULL)
{
if(cfile->d_name[0]!='.')
break;
}
/*compile c file*/
//child process
if((pid=fork())==0)
{
fullpath=realloc(fullpath, sizeof(char)*(strlen(fullpath)+strlen(cfile->d_name)+1));
outpath=(char*)calloc(strlen(fullpath)+strlen(OUT_NAME)+1,sizeof(char));
strcpy(outpath,fullpath);
strcat(fullpath,cfile->d_name);
strcat(outpath,OUT_NAME);
execl("/usr/bin/gcc", "/usr/bin/gcc", "-o", outpath, fullpath,NULL);
}
else
{
wait(NULL);
}
//create output file path
outputpath=calloc(strlen(fullpath)+strlen(OUTPUTFILE_NAME)+1,sizeof(char));
strcpy(outputpath,fullpath);
strcat(outputpath,OUTPUTFILE_NAME);
inputpath=(char*)calloc(strlen(buff)+1,sizeof(char));
//get input file path from buffer
for(j=0,buffIndex++;buff[buffIndex]!='\n';buffIndex++,j++)
{
inputpath[j]=buff[buffIndex];
}
////Untill here works perfectly////
//child process
if((pid=fork())==0)
{
fullpath=realloc(fullpath, sizeof(char)*(strlen(fullpath)+strlen(OUT_NAME)+1));
strcat(fullpath, OUT_NAME);
//re-open input file and associate it with stdin
freopen(inputpath, "r", stdin);
//re-open output file and associate it with stdout
freopen(outputpath, "w", stdout);
execl(fullpath,inputpath, NULL);
}
else
{
wait(NULL);
}
}
* inputpath是我的程序输入准备的文件的完整路径。
* outputpath是我想要保存程序输出的文件的完整路径。
我肯定做错了什么,因为我得到以下错误:
/home/aviad/workspace/test/dean/input.txt~: file not recognized: File truncated
collect2: error: ld returned 1 exit status
/home/aviad/workspace/test/jjang/fileoutput.txt: file not recognized: File truncated
collect2: error: ld returned 1 exit status
任何帮助吗?
那些看起来像编译器/链接器错误...你确定你没有,呃,试图编译你的.txt文件......? – FatalError 2013-03-23 17:43:07
怎么样?我没有在任何地方调用gcc ......这些错误来自这段代码。 – Jjang 2013-03-23 17:47:28
不确定。发布一个更完整的例子,以及你如何执行你的程序,它可能会提供一些见解。你没有偶然给你的程序命名为'ld',是吗? – FatalError 2013-03-23 17:48:36