1 /* 2 * Run a script accessing a filesystem. 3 * 4 * Copyright (C) 2022, 2024 Paul Boddie <paul@boddie.org.uk> 5 * 6 * This program is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU General Public License as 8 * published by the Free Software Foundation; either version 2 of 9 * the License, or (at your option) any later version. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, 19 * Boston, MA 02110-1301, USA 20 */ 21 22 #include <stdio.h> 23 #include <string.h> 24 25 #include "input.h" 26 #include "ops.h" 27 28 29 30 /* Line buffer size. */ 31 32 static int BUFSIZE = 4096; 33 34 /* Maximum number of arguments in scripts. */ 35 36 static const int MAX_ARGS = 32; 37 38 39 40 /* Read operations from a script file. */ 41 42 int run_script(int argc, char *argv[]) 43 { 44 FILE *fp; 45 char buffer[BUFSIZE]; 46 enum op_results op_result; 47 int num_args; 48 char *args[MAX_ARGS]; 49 int i, use_stdin; 50 51 for (i = 0; i < argc; i++) 52 { 53 /* Test for standard input as a special filename. */ 54 55 use_stdin = !strcmp(argv[i], "-"); 56 57 if (use_stdin) 58 fp = stdin; 59 else 60 fp = fopen(argv[i], "r"); 61 62 while (1) 63 { 64 /* Show a prompt if employing standard input. */ 65 66 if (use_stdin) 67 printf("> "); 68 69 /* Read and parse the input line, running any specified command. */ 70 71 if (read_line(fp, buffer, BUFSIZE) == NULL) 72 break; 73 74 parse_line(buffer, buffer + strlen(buffer), &num_args, args, MAX_ARGS); 75 76 /* Permit commands with and without arguments. */ 77 78 if (num_args >= 1) 79 { 80 op_result = run_operation(args[0], num_args - 1, &args[1]); 81 82 if (handle_op_result(args[0], op_result) && !use_stdin) 83 return 1; 84 } 85 } 86 87 /* Close normal files. */ 88 89 if (!use_stdin) 90 fclose(fp); 91 } 92 93 printf("End of script.\n"); 94 return 0; 95 } 96 97 /* vim: tabstop=4 expandtab shiftwidth=4 98 */