Swapnil Koshti
Swapnil Koshti

Reputation: 29

Want to run C program exectable from java

I have a C Program executable file which I want to run from java,Also I want to give inputs for the program at runtime. I have written below code but it doesn't show anything.

Java program :

public static void main(String[] args) throws IOException {

    String[] command = {"CMD", "/C", "D:\\TestApp.exe"};
    ProcessBuilder probuilder = new ProcessBuilder( command );

    Process process = probuilder.start();

    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    System.out.printf("Output of running %s is:\n",Arrays.toString(command));
    while ((line = br.readLine()) != null) {
        System.out.println(line);            
    }

    try {
        int exitValue = process.waitFor();
        System.out.println("\n\nExit Value is " + exitValue);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

And My C Program is below:

void main()
{
    int x,y,res;
    printf("\nEnter the First No:");
    scanf("%d",&x);

    printf("\nEnter the Second No:");
    scanf("%d",&y);

    res = x + y;
    printf ("\nResult is %d",res);
    getch();
}

Please tell me solution, Thanx in advance. Also tell me the code to provide inputs at runtime

Upvotes: 2

Views: 580

Answers (1)

janos
janos

Reputation: 124648

The C program expects input. To write to the standard input of the process, write to process.getOutputStream(), for example:

OutputStream stdin = process.getOutputStream();
stdin.write("3 4\n".getBytes());
stdin.flush();

The terminating \n is important, as the process is waiting for a newline character. The .flush() call is important too, as Java buffers the writes, and this call forces to write out the content of the buffer.

With these lines added to your code, you will get the output:

Output of running [/path/to/program] is:

Enter the First No:
Enter the Second No:
Result is 7


Exit Value is 0

Upvotes: 1

Related Questions