| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- #include <stdio.h>
- #include <fcntl.h>
- #include <string.h>
- #include <unistd.h>
- #include <errno.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #define BUF_SIZE 256
- const char* VERSION = "1.0";
- void check_version_arg(int argc, char** argv) {
- for (int i = 0; i < argc; i++) {
- if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
- printf("cppfile version: %s\n", VERSION);
- exit(0);
- }
- }
- }
- int main(int argc, char* argv[]) {
- if (argc <= 1) {
- printf("Too few arguments\n");
- return 1;
- }
- check_version_arg(argc, argv);
- const bool HAS_INCLUDES = argc > 2;
- char name[strlen(argv[1]) + 2];
- strcpy(name, argv[1]);
- strcat(name, ".cpp");
- char path[BUF_SIZE] = "./";
- strcat(path, name);
- open(path, O_RDONLY, 0);
-
- if (errno == 0) {
- printf("File already exists.\n");
- return 2;
- }
- const int fd = creat(path, S_IRUSR | S_IWUSR | S_IROTH);
-
- int includes_n = argc - 2;
- int lines_n = 4 + includes_n;
- char* lines[BUF_SIZE];
- int lines_i = 0;
- if (HAS_INCLUDES) {
- for (int i = 2; i < argc; i++) {
- char* line = (char*) malloc(BUF_SIZE);
- strcpy(line, "#include <");
- strcat(line, argv[i]);
- strcat(line, ">\n");
- lines[lines_i] = line;
- lines_i++;
- }
- lines[lines_i] = "\n";
- lines[++lines_i] = "int main() {\n\n";
- lines[++lines_i] = " return 0;\n";
- lines[++lines_i] = "}";
- } else {
- lines[lines_i] = "int main() {\n\n";
- lines[++lines_i] = " return 0;\n";
- lines[++lines_i] = "}";
- lines_n--;
- }
- for (int i = 0; i < lines_n; i++) {
- write(fd, lines[i], strlen(lines[i]));
- }
- close(fd);
- char command[5 + strlen(name)];
- strcpy(command, "nvim ");
- strcat(command, name);
- system(command);
- return 0;
- }
|