cfile.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. typedef struct node {
  9. char* string;
  10. struct node* next;
  11. } fifo;
  12. void fifo_append(fifo* head, char* new_string);
  13. char* fifo_read(fifo** head);
  14. int main(int argc, char* argv[]) {
  15. if (argc <= 1) {
  16. printf("Too few arguments\n");
  17. return 1;
  18. }
  19. printf("%d\n", argc);
  20. char name[strlen(argv[1]) + 2];
  21. strcpy(name, argv[1]);
  22. strcat(name, ".c");
  23. char path[BUF_SIZE] = "./";
  24. strcat(path, name);
  25. open(path, O_RDONLY, 0);
  26. if (errno == 0) {
  27. printf("File already exists.\n");
  28. return 2;
  29. }
  30. errno = 0;
  31. const int fd = creat(path, S_IRUSR | S_IWUSR | S_IROTH);
  32. int includes_n = argc - 2;
  33. int lines_n = 4 + includes_n;
  34. fifo* lines_head = (fifo*) malloc(sizeof(fifo));
  35. lines_head->string = "";
  36. lines_head->next = NULL;
  37. if (argc > 2) {
  38. for (int i = 2; i < argc; i++) {
  39. char line[BUF_SIZE] = "#include <";
  40. strcat(line, argv[i]);
  41. strcat(line, ".h>\n");
  42. fifo_append(lines_head, line);
  43. }
  44. fifo_append(lines_head, "\n");
  45. }
  46. fifo_append(lines_head, "int main() {\n\n");
  47. fifo_append(lines_head, " return 0;\n");
  48. fifo_append(lines_head, "}");
  49. for (int i = 0; i < lines_n; i++) {
  50. write(fd, fifo_read(&lines_head), strlen(lines_head->string));
  51. }
  52. close(fd);
  53. char command[5 + strlen(name)];
  54. strcpy(command, "nvim ");
  55. strcat(command, name);
  56. system(command);
  57. return 0;
  58. }
  59. void fifo_append(fifo* head, char* string) {
  60. fifo* last = head;
  61. char* new_string = (char*) malloc(sizeof(char) * strlen(string));
  62. strcpy(new_string, string);
  63. while (last->next != NULL)
  64. last = last->next;
  65. fifo* new_node = (fifo*) malloc(sizeof(fifo));
  66. new_node->string = new_string;
  67. new_node->next = NULL;
  68. last->next = new_node;
  69. }
  70. char* fifo_read(fifo** head) {
  71. char* return_value = (*head)->string;
  72. fifo* prev_head = *head;
  73. *head = (*head)->next;
  74. free(prev_head);
  75. return return_value;
  76. }