From afbcaac1aebe9b4a8f1603421285dbcb97c912ee Mon Sep 17 00:00:00 2001 From: Aleksandr Lebedev Date: Thu, 19 Feb 2026 17:49:56 +0100 Subject: [PATCH] Script files support - readline accepts stream to read from - fixed issues with EOF - arsh can be called with a file path as a second parameter, that will be interpreted --- main.c | 47 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/main.c b/main.c index 4dc2c3d..7133072 100644 --- a/main.c +++ b/main.c @@ -21,22 +21,28 @@ void sigint_handler(int signo) } static constexpr size_t max_line = 1024; static char string_buffer[max_line]; -char* readline(char* print) +char* readline(char* print, FILE* stream) { if(print) { printf("%s", print); } - if((fgets(string_buffer, max_line, stdin) == NULL) && ferror(stdin)) + if(fgets(string_buffer, max_line, stream) == NULL) { - perror("fgets error"); + if (feof(stdin)) + { + return NULL; // Ctrl+D + } + if(ferror(stream)) + { + perror("fgets error"); + clearerr(stdin); + return NULL; + } + return NULL; } size_t length = strlen(string_buffer); - if(length == 0) - { - return NULL; - } //Remove trailing \n if (length > 0 && string_buffer[length - 1] == '\n') { @@ -73,8 +79,20 @@ int cd(char* path) return chdir(path); } -int main() +int main(int argc, const char* argv[]) { + FILE* stream = stdin; + char* prompt = "arsh> "; + if(argc == 2) + { + FILE* file = fopen(argv[1], "r"); + if(file) + { + stream = file; + prompt = NULL; + } + } + struct sigaction s; s.sa_handler = sigint_handler; sigemptyset(&s.sa_mask); @@ -92,17 +110,26 @@ int main() while(true) { - char* input = readline("arsh> "); + char* input = readline(prompt, stream); if(input == NULL) //CTRL + D { - printf("\nexit\n"); + if(prompt) + { + printf("\nexit\n"); + } exit(0); } + + // After that line you need cleanup char** command = split_input(input); if(command[0] == NULL) { goto cleanup; } + if(strlen(command[0]) >= 1 && command[0][0] == '#') + { + goto cleanup; + } if(strcmp(command[0], "cd") == 0) {