cppfile.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. const char* VERSION = "1.0";
  10. void check_version_arg(int argc, char** argv) {
  11. for (int i = 0; i < argc; i++) {
  12. if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
  13. printf("cppfile version: %s\n", VERSION);
  14. exit(0);
  15. }
  16. }
  17. }
  18. int main(int argc, char* argv[]) {
  19. if (argc <= 1) {
  20. printf("Too few arguments\n");
  21. return 1;
  22. }
  23. check_version_arg(argc, argv);
  24. const bool HAS_INCLUDES = argc > 2;
  25. char name[strlen(argv[1]) + 2];
  26. strcpy(name, argv[1]);
  27. strcat(name, ".cpp");
  28. char path[BUF_SIZE] = "./";
  29. strcat(path, name);
  30. open(path, O_RDONLY, 0);
  31. if (errno == 0) {
  32. printf("File already exists.\n");
  33. return 2;
  34. }
  35. const int fd = creat(path, S_IRUSR | S_IWUSR | S_IROTH);
  36. int includes_n = argc - 2;
  37. int lines_n = 4 + includes_n;
  38. char* lines[BUF_SIZE];
  39. int lines_i = 0;
  40. if (HAS_INCLUDES) {
  41. for (int i = 2; i < argc; i++) {
  42. char* line = (char*) malloc(BUF_SIZE);
  43. strcpy(line, "#include <");
  44. strcat(line, argv[i]);
  45. strcat(line, ">\n");
  46. lines[lines_i] = line;
  47. lines_i++;
  48. }
  49. lines[lines_i] = "\n";
  50. lines[++lines_i] = "int main() {\n\n";
  51. lines[++lines_i] = " return 0;\n";
  52. lines[++lines_i] = "}";
  53. } else {
  54. lines[lines_i] = "int main() {\n\n";
  55. lines[++lines_i] = " return 0;\n";
  56. lines[++lines_i] = "}";
  57. lines_n--;
  58. }
  59. for (int i = 0; i < lines_n; i++) {
  60. write(fd, lines[i], strlen(lines[i]));
  61. }
  62. close(fd);
  63. char command[5 + strlen(name)];
  64. strcpy(command, "nvim ");
  65. strcat(command, name);
  66. system(command);
  67. return 0;
  68. }