[英]Executing program from c code using System
I'm writing c program which get as inputs execution fileName and txt fileName. 我正在写c程序,它以输入执行fileName和txt fileName作为输入。 My program should run the exe file with the strings from the txt file in the next format: ./exename ./fileName.. I read each line from the text file with fgets() function.
我的程序应使用txt文件中的字符串以以下格式运行exe文件:./exename ./fileName ..我使用fgets()函数从文本文件中读取每一行。 I'm using system() function to run the exe from my code.
我正在使用system()函数从我的代码运行exe。 this is my code
这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define READSIZE 100
int main(int argc,char *argv[]){
FILE * src;
//char path[] ="home/omriz/playGround/Cyber/ex4/1/prog1strings.txt";
char buffer[READSIZE];
int i;
int status;
char *result = malloc(strlen(argv[2]) + strlen(buffer)+2);//+1 for the zero-terminator
if(argc < 3){
printf("prototype error <exe file to run><strings txt file txt>\n");
return -1;
}
printf ("exe file path is : %s \n",argv[1]);
printf ("src file path is : %s \n",argv[2]);
src = fopen(argv[2],"r");
while(!(feof(src))){
fgets(buffer,READSIZE,src);
printf("string read from txt file is: %s\n",buffer);
*result = malloc(strlen(argv[2])+strlen(buffer)+2);
strcpy(result,argv[1]);
strcat(result," ");
strcat(result, buffer);
printf("result is %s\n",result);
printf("before sys command\n");
status = system(result);
printf("status value is %d\n",status);
}
printf("we reached the end of the string.txt file\n");
free(result);
fclose(src);
}
The problem is that the program exits before it read all the lines from the text file and I don't know why. 问题在于该程序在从文本文件读取所有行之前退出,我不知道为什么。
the exe file which I run from my code should return string value like "True" or "False" how can I catch this values considering using the system() function? 我从我的代码运行的exe文件应该返回字符串值,例如“ True”或“ False”,考虑使用system()函数,如何捕获此值?
thanks. 谢谢。
*result = malloc(strlen(argv[2])+strlen(buffer)+2);
result is a char* , so this is an error (just remove the *) 结果是一个char *,所以这是一个错误(只需删除*)
edit: a little bit of explaination 编辑:一点解释
malloc return a void *, so here you are setting the 1byte pointed by result to the pointer return by malloc malloc返回一个空*,因此在这里您将结果指向的1个字节设置为malloc返回的指针
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.