paul@294 | 1 | /* |
paul@294 | 2 | * Elementary input utilities. |
paul@294 | 3 | * |
paul@591 | 4 | * Copyright (C) 2022, 2024 Paul Boddie <paul@boddie.org.uk> |
paul@294 | 5 | * |
paul@294 | 6 | * This program is free software; you can redistribute it and/or |
paul@294 | 7 | * modify it under the terms of the GNU General Public License as |
paul@294 | 8 | * published by the Free Software Foundation; either version 2 of |
paul@294 | 9 | * the License, or (at your option) any later version. |
paul@294 | 10 | * |
paul@294 | 11 | * This program is distributed in the hope that it will be useful, |
paul@294 | 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
paul@294 | 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
paul@294 | 14 | * GNU General Public License for more details. |
paul@294 | 15 | * |
paul@294 | 16 | * You should have received a copy of the GNU General Public License |
paul@294 | 17 | * along with this program; if not, write to the Free Software |
paul@294 | 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, |
paul@294 | 19 | * Boston, MA 02110-1301, USA |
paul@294 | 20 | */ |
paul@294 | 21 | |
paul@591 | 22 | #include <stdio.h> |
paul@294 | 23 | #include <string.h> |
paul@294 | 24 | |
paul@294 | 25 | #include "input.h" |
paul@294 | 26 | |
paul@294 | 27 | |
paul@294 | 28 | |
paul@591 | 29 | /* Read a line from a file into the given buffer, removing any newline. */ |
paul@294 | 30 | |
paul@591 | 31 | char *read_line(FILE *fp, char *buffer, size_t bufsize) |
paul@591 | 32 | { |
paul@591 | 33 | char *last; |
paul@294 | 34 | |
paul@591 | 35 | if (fgets(buffer, bufsize, fp) == NULL) |
paul@591 | 36 | return NULL; |
paul@294 | 37 | |
paul@591 | 38 | last = buffer + strlen(buffer) - 1; |
paul@294 | 39 | |
paul@591 | 40 | if ((last >= buffer) && (*last == '\n')) |
paul@591 | 41 | *last = '\0'; |
paul@294 | 42 | |
paul@591 | 43 | return buffer; |
paul@294 | 44 | } |
paul@294 | 45 | |
paul@294 | 46 | /* Parse the text in the given region, returning details of arguments. */ |
paul@294 | 47 | |
paul@294 | 48 | void parse_line(char *start, char *end, int *num_args, char *args[], const int max_args) |
paul@294 | 49 | { |
paul@294 | 50 | *num_args = 0; |
paul@294 | 51 | |
paul@294 | 52 | while ((start != NULL) && (start < end) && (*num_args < max_args)) |
paul@294 | 53 | { |
paul@294 | 54 | args[*num_args] = start; |
paul@294 | 55 | (*num_args)++; |
paul@294 | 56 | |
paul@294 | 57 | /* NOTE: Only handling spaces as delimiters. */ |
paul@294 | 58 | |
paul@294 | 59 | start = strchr(start, ' '); |
paul@294 | 60 | |
paul@294 | 61 | if (start != NULL) |
paul@294 | 62 | { |
paul@294 | 63 | *start = '\0'; |
paul@294 | 64 | |
paul@294 | 65 | if (start < end) |
paul@294 | 66 | start++; |
paul@294 | 67 | } |
paul@294 | 68 | } |
paul@294 | 69 | } |
paul@294 | 70 | |
paul@294 | 71 | /* vim: tabstop=4 expandtab shiftwidth=4 |
paul@294 | 72 | */ |