cfile.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <errno.h>
  6. #include <stdlib.h>
  7. #include <stdbool.h>
  8. #define BUF_SIZE 256
  9. int main(int argc, char* argv[]) {
  10. if (argc <= 1) {
  11. printf("Too few arguments\n");
  12. return 1;
  13. }
  14. const bool HAS_INCLUDES = argc > 2;
  15. char name[strlen(argv[1]) + 2];
  16. strcpy(name, argv[1]);
  17. strcat(name, ".c");
  18. char path[BUF_SIZE] = "./";
  19. strcat(path, name);
  20. open(path, O_RDONLY, 0);
  21. if (errno == 0) {
  22. printf("File already exists.\n");
  23. return 2;
  24. }
  25. errno = 0;
  26. const int fd = creat(path, S_IRUSR | S_IWUSR | S_IROTH);
  27. int includes_n = argc - 2;
  28. int lines_n = 4 + includes_n;
  29. char* lines[BUF_SIZE];
  30. int lines_i = 0;
  31. if (HAS_INCLUDES) {
  32. for (int i = 2; i < argc; i++) {
  33. char* line = (char*) malloc(BUF_SIZE);
  34. strcpy(line, "#include <");
  35. strcat(line, argv[i]);
  36. strcat(line, ".h>\n");
  37. lines[lines_i] = line;
  38. lines_i++;
  39. }
  40. lines[lines_i] = "\n";
  41. lines[++lines_i] = "int main() {\n\n";
  42. lines[++lines_i] = " return 0;\n";
  43. lines[++lines_i] = "}";
  44. } else {
  45. lines[lines_i] = "int main() {\n\n";
  46. lines[++lines_i] = " return 0;\n";
  47. lines[++lines_i] = "}";
  48. lines_n--;
  49. }
  50. for (int i = 0; i < lines_n; i++) {
  51. write(fd, lines[i], strlen(lines[i]));
  52. }
  53. close(fd);
  54. char command[5 + strlen(name)];
  55. strcpy(command, "nvim ");
  56. strcat(command, name);
  57. system(command);
  58. return 0;
  59. }