0

I'm writing c program which get as inputs execution fileName and 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. I'm using system() function to run the exe from my code. 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?

thanks.

Omri Ziner
  • 83
  • 1
  • 6
  • You have a problem with the result memory allocation. I think that instead *result = malloc(strlen(argv[2])+strlen(buffer)+2); you wanted to write result = .... (now you are ovverriding the first 4 bytes with the pointer to the new result memory) Another thing- are you sure that you have assigned enough memory for the command? – sborpo May 20 '17 at 17:02

1 Answers1

1
*result = malloc(strlen(argv[2])+strlen(buffer)+2);

result is a char* , so this is an error (just remove the *)

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

Riccardo Bonafede
  • 610
  • 1
  • 9
  • 17
  • Thanks, it helped and solved the first problem. now the program read all the strings from the text file. Still I'm waiting for some help about get the strings value from the exe I run with system. – Omri Ziner May 21 '17 at 04:20
  • you have to create a pipe, see [here](https://stackoverflow.com/questions/7292642/grabbing-output-from-exec) – Riccardo Bonafede May 21 '17 at 11:55