Bladeren bron

added cppfile

Aaro Saila 1 jaar geleden
bovenliggende
commit
d056a1f43c
1 gewijzigde bestanden met toevoegingen van 78 en 0 verwijderingen
  1. 78 0
      cppfile.c

+ 78 - 0
cppfile.c

@@ -0,0 +1,78 @@
+#include <stdio.h>
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <stdbool.h>
+
+#define BUF_SIZE 256
+
+int main(int argc, char* argv[]) {
+  if (argc <= 1) {
+    printf("Too few arguments\n");
+    return 1;
+  }
+
+  const bool HAS_INCLUDES = argc > 2;
+  char name[strlen(argv[1]) + 2];
+  strcpy(name, argv[1]);
+  strcat(name, ".cpp");
+
+  char path[BUF_SIZE] = "./";
+
+  strcat(path, name);
+
+  open(path, O_RDONLY, 0);
+  
+  if (errno == 0) {
+    printf("File already exists.\n");
+    return 2;
+  }
+  errno = 0;
+
+  const int fd = creat(path, S_IRUSR | S_IWUSR | S_IROTH);
+  
+  int includes_n = argc - 2;
+  int lines_n = 4 + includes_n;
+
+  char* lines[BUF_SIZE];
+
+  int lines_i = 0;
+  if (HAS_INCLUDES) {
+    for (int i = 2; i < argc; i++) {
+      char* line = (char*) malloc(BUF_SIZE);
+      strcpy(line, "#include <");
+      strcat(line, argv[i]);
+      strcat(line, ">\n");
+
+      lines[lines_i] = line;
+
+      lines_i++;
+    }
+
+    lines[lines_i] = "\n";
+    lines[++lines_i] = "int main() {\n\n";
+    lines[++lines_i] = "  return 0;\n";
+    lines[++lines_i] = "}";
+  } else {
+    lines[lines_i] = "int main() {\n\n";
+    lines[++lines_i] = "  return 0;\n";
+    lines[++lines_i] = "}";
+    lines_n--;
+  }
+
+  for (int i = 0; i < lines_n; i++) {
+    write(fd, lines[i], strlen(lines[i]));
+  }
+
+  close(fd);
+
+  char command[5 + strlen(name)];
+  strcpy(command, "nvim ");
+  strcat(command, name);
+
+  system(command);
+
+  return 0;
+}