cfile.c 1.3 KB

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