Save gcc compile status to a text file for Java
- by JohnBore
I'm making a C Assessment Program through Java, which has a bunch of programming questions for C, and it lets the user input an answer in the form of C code, and then press a "Compile" button, which is linked to a bat file that runs the user input code through gcc.
I've got the input and compiling working, but I need to get the output from the compiler and get that to print textarea within the program. I can get a simple "Hello, world" compiling, but I'm having trouble getting programs that require a user input with scanf, for example, to be printed.
else if(e.getSource().equals(compile)){
if(questionNumber<1){
JOptionPane.showMessageDialog(programFrame, "Please start the assessment", "Compile Error", JOptionPane.ERROR_MESSAGE);
}
else{
FileOutputStream fileWrite;
try {
fileWrite = new FileOutputStream("demo/demo.c");
new PrintStream(fileWrite).println(input.getText());//saves what the user has entered in to a C source file
fileWrite.close();
@SuppressWarnings("unused")
Process process = Runtime.getRuntime().exec("cmd /c compile.bat");//runs the batch file to compile the source file
compileCode();
try{
fileStream = new FileInputStream("demo/output.txt");
inputStream = new DataInputStream(fileStream);
bufferRead = new BufferedReader(new InputStreamReader(inputStream));
while((stringLine = bufferRead.readLine())!=null){
compiled.append(stringLine);
compiled.append("\n");
}
inputStream.close();
}
catch(IOException exc){
System.err.println("Unable to read file");
System.exit(-1);
}
}
catch (IOException exc) {
JOptionPane.showMessageDialog(programFrame, "Demo file not found", "File Error", JOptionPane.ERROR_MESSAGE);
}
}
This is the actionPerformed method for the "Compile" button, the compileCode() is the JFrame that displays the output and "compiled" is the textArea for the output.
My batch file is:
C:
cd dev-cpp\bin
gcc.exe H:\workspace\QuestionProgram\demo\demo.c -o demo > H:\workspace\QuestionProgram\demo\compilestatus.txt
demo > H:\workspace\QuestionProgram\demo\output.txt
I'm not sure how I can do it, so the frame is created for the output of the code if the code requires a user input as the command prompt doesn't open without adding "START" to .exec(), but then the frame appears before the program has finished running.
Also, how would I get the output of the compiler if the compile fails because of an error? The way I've got it in my batch file at the moment doesn't put anything in a text file if it fails.