cr.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define MAX_ARG_LENGTH 1000
  5. #define VERSION "1.0"
  6. // TODO: Check file modification date and only recompile if binary is older.
  7. typedef struct {
  8. char full_path[MAX_ARG_LENGTH];
  9. char name[MAX_ARG_LENGTH];
  10. char exec_name[MAX_ARG_LENGTH];
  11. char dest_path[MAX_ARG_LENGTH + 6]; // /tmp/ + exec_name + \0
  12. } file_info;
  13. void parse_flags(char argv[][MAX_ARG_LENGTH], file_info* fi) {
  14. if (strcmp(argv[1], "--version") == 0) {
  15. printf("cr version: %s\n", VERSION);
  16. exit(0);
  17. }
  18. strncpy(fi->full_path, argv[1], (sizeof(fi->full_path) / sizeof(char)) - 1);
  19. const char* delim = "/";
  20. char* first_token = strtok(argv[1], delim);
  21. if (first_token == NULL) {
  22. strncpy(fi->name, argv[1], (sizeof(fi->full_path) / sizeof(char)) - 1);
  23. } else {
  24. char* prev_token = first_token;
  25. char* cur_token = first_token;
  26. while (cur_token != NULL) {
  27. prev_token = cur_token;
  28. cur_token = strtok(NULL, delim);
  29. }
  30. strncpy(fi->name, prev_token, (sizeof(fi->full_path) / sizeof(char)) - 1);
  31. }
  32. strncpy(fi->exec_name, fi->name, sizeof(fi->exec_name) / sizeof(char));
  33. fi->exec_name[strlen(fi->exec_name) - 2] = '\0';
  34. strncpy(fi->dest_path, "/tmp/", (sizeof(fi->dest_path) / sizeof(char)) - 1);
  35. strncat(fi->dest_path, fi->exec_name, (sizeof(fi->dest_path) / sizeof(char)) - 1);
  36. }
  37. int main(int argc, char* argv[]) {
  38. if (argc < 2) {
  39. printf("ERROR: Path to C file must be specified.\n");
  40. return 1;
  41. }
  42. file_info fi;
  43. char argv_copy[argc][MAX_ARG_LENGTH];
  44. for (int i = 0; i < argc; i++) {
  45. strncpy(argv_copy[i], argv[i], MAX_ARG_LENGTH);
  46. }
  47. parse_flags(argv_copy, &fi);
  48. const int cmd_max_len = strlen("gcc ") + sizeof(fi.full_path) / sizeof(char) + strlen(" -o ") + sizeof(fi.dest_path) / sizeof(char);
  49. char cmd[cmd_max_len];
  50. strcpy(cmd, "gcc ");
  51. strcat(cmd, fi.full_path);
  52. strcat(cmd, " -o ");
  53. strcat(cmd, fi.dest_path);
  54. strcat(cmd, "\0");
  55. system(cmd);
  56. system(fi.dest_path);
  57. return 0;
  58. }