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
This commit is contained in:
Aleksandr Lebedev 2026-02-19 17:49:56 +01:00
parent e96ae4b4a2
commit afbcaac1ae

47
main.c
View file

@ -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)
{