cfile.c 2.0 KB

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