Browse Source

first commit, cfile tool

Aaro Saila 2 years ago
commit
afafe68f2d
1 changed files with 75 additions and 0 deletions
  1. 75 0
      cfile.c

+ 75 - 0
cfile.c

@@ -0,0 +1,75 @@
+#include <stdio.h>
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdlib.h>
+
+#define BUF_SIZE 256
+
+int main(int argc, char* argv[]) {
+  if (argc <= 1) {
+    printf("Too few arguments\n");
+    return 1;
+  }
+
+  printf("%d\n", argc);
+
+  for (int i = 0; i < argc; i++) {
+    printf("%s\n", argv[i]);
+  }
+
+  char name[strlen(argv[1]) + 2];
+  strcpy(name, argv[1]);
+  strcat(name, ".c");
+
+  char path[BUF_SIZE] = "./";
+
+  strcat(path, name);
+
+  int open_s = 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 = 5 + includes_n;
+
+  char* lines[lines_n] = {};
+  int lines_i = 0;
+
+  if (argc > 2) {
+    for (int i = 2; i < argc; i++) {
+      char line[BUF_SIZE] = "#include <";
+      strcat(line, argv[i]);
+      strcat(line, ".h>\n");
+      lines[lines_i] = line;
+      lines_i++;
+    }
+    lines[lines_i] = "\n";
+  }
+
+  lines[++lines_i] = "int main() {\n";
+  lines[++lines_i] = "\n";
+  lines[++lines_i] = "  return 0;\n";
+  lines[++lines_i] = "}";
+
+  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;
+}