package Compiler; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.nio.file.Paths; import java.nio.file.Files; public class ExecuteC { public void compileAndExecuteC(List code, String filename) { writeProgram(code, filename); if (!compileC(filename)){ String output = runProgram(filename); System.out.println(output); } else{ Language.displayError("Runtime Error"); } } public void compileAndExecuteC(List code){ compileAndExecuteC(code, "main"); } public void writeProgram(List codeLines, String filename){ try { Files.createDirectories(Paths.get("build")); } catch (IOException e) { e.printStackTrace(); } BufferedWriter output = null; try { File file = Paths.get("build", String.format("%s.c", filename)).toFile(); output = new BufferedWriter(new FileWriter(file)); for(String line:codeLines){ output.write(line+"\n"); } output.close(); } catch ( IOException e ) { e.printStackTrace(); } } public Boolean compileC(String filename){ try{ String s= null; Process p; if (System.getProperty("os.name").equals("Linux")) { p = Runtime.getRuntime().exec(String.format("gcc build/%s.c -o build/%s", filename, filename)); } else { p = Runtime.getRuntime().exec(String.format( "cmd /C gcc %s -o %s", Paths.get("build", String.format("%s.c", filename)).toString(), Paths.get("build", String.format("%s.exe", filename)).toString() )); } BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); boolean error=false; while ((s = stdError.readLine()) != null) { error=true; } return error; } catch (IOException e){ e.printStackTrace(); } return false; } public String runProgram(String filename){ try{ ProcessBuilder probuilder; if (System.getProperty("os.name").equals("Linux")) { String[] command = {"sh", "-c", String.format("./build/%s", filename)}; probuilder = new ProcessBuilder(command); } else { String[] command = {"cmd", "/C", Paths.get("build", String.format("%s.exe", filename)).toString()}; probuilder = new ProcessBuilder(command); } Process p = probuilder.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); String s = null; String output=""; while ((s = stdInput.readLine()) != null) { output+=s; } return output; } catch (IOException e){ e.printStackTrace(); } System.out.println(); return null; } }