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.Path; import java.nio.file.Files; public class ExecuteC { Path buildToDir; String filename; public void compileAndExecuteC(List code, String outPathStr, boolean executeAfter, boolean leaveCFile) { Path outPath = Path.of(outPathStr); int numElements = outPath.getNameCount(); filename = outPath.getName(numElements - 1).toString(); if (numElements == 1) { buildToDir = Paths.get("build"); } else { buildToDir = outPath.subpath(0, numElements - 1); } try { Files.createDirectories(buildToDir); } catch (IOException e) { e.printStackTrace(); } File cProgram = writeProgram(code); if (!compileC()) { if (executeAfter) { String output = runProgram(); System.out.println(output); } } else { Language.displayError(0, "Runtime Error"); } if (!leaveCFile) { cProgram.delete(); } } public void compileAndExecuteC(List code) { compileAndExecuteC(code, "main", true, true); } public File writeProgram(List codeLines){ BufferedWriter output = null; File file = null; try { file = Paths.get(buildToDir.toString(), 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(); } return file; } public Boolean compileC(){ try{ String s= null; Process p; if (System.getProperty("os.name").equals("Linux")) { p = Runtime.getRuntime().exec(String.format( "gcc %s/%s.c -o %s/%s", buildToDir.toString(), filename, buildToDir.toString(), filename )); } else { p = Runtime.getRuntime().exec(String.format( "cmd /C gcc %s -o %s", Paths.get(buildToDir.toString(), String.format("%s.c", filename)).toString(), Paths.get(buildToDir.toString(), 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(){ try{ ProcessBuilder probuilder; if (System.getProperty("os.name").equals("Linux")) { String[] command = {"sh", "-c", Paths.get(buildToDir.toString(), filename).toString()}; probuilder = new ProcessBuilder(command); } else { String[] command = {"cmd", "/C", Paths.get(buildToDir.toString(), 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+"\n"; } return output; } catch (IOException e){ e.printStackTrace(); } System.out.println(); return null; } }