Line data Source code
1 : /*
2 : * sadplay - AdLib music player with graphics.
3 : *
4 : * main_support.cc - implementation of the support functions for main.
5 : *
6 : * Copyright (C) 2019 Marco Confalonieri <marco at marcoconfalonieri.it>
7 : *
8 : * This program is free software: you can redistribute it and/or modify
9 : * it under the terms of the GNU General Public License as published by
10 : * the Free Software Foundation, either version 3 of the License, or
11 : * (at your option) any later version.
12 : *
13 : * This program is distributed in the hope that it will be useful,
14 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 : * GNU General Public License for more details.
17 : *
18 : * You should have received a copy of the GNU General Public License
19 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 : */
21 :
22 : #include "main_support.h"
23 :
24 : #include <fstream>
25 : #include <iostream>
26 :
27 : #include <unistd.h>
28 :
29 : using std::ifstream;
30 : using std::string;
31 :
32 : // Reads the file list from a text file or the standard input.
33 6 : void read_file_list_from_file(sadplay_args* args, string file, std::istream &input) {
34 : std::istream* file_list;
35 :
36 : // Open a file or assign our stream to standard input.
37 6 : if (file == "-") {
38 : file_list = &input;
39 : } else {
40 4 : file_list = new ifstream(file);
41 : }
42 :
43 : // Read the stream line by line.
44 6 : string line;
45 48 : while (std::getline(*file_list, line)) {
46 18 : args->file_list.push_back(line);
47 : }
48 :
49 : // if the file list is not in the standard input, closes the stream and
50 : // delete it.
51 6 : if (file_list != &input) {
52 4 : ((ifstream*) file_list)->close();
53 4 : delete file_list;
54 : }
55 6 : }
56 :
57 : // Reads the file list from the command line arguments.
58 4 : void read_file_list_from_argv(sadplay_args* args, int argc, char* argv[], int opt_index) {
59 16 : for (int idx = opt_index; idx < argc; idx++) {
60 36 : args->file_list.push_back(string(argv[idx]));
61 : }
62 4 : }
63 :
64 : // Reads the command line arguments.
65 6 : void read_command_line(sadplay_args* args, int argc, char* argv[]) {
66 : int c;
67 10 : string file;
68 6 : bool file_list_used = false;
69 16 : while ((c = getopt(argc, argv, "vl:f:")) != -1) {
70 12 : switch (c) {
71 6 : case 'v':
72 6 : args->verbose = true;
73 6 : break;
74 : case 'l':
75 6 : args->log_file = string(optarg);
76 2 : break;
77 : case 'f':
78 6 : file = string(optarg);
79 2 : file_list_used = true;
80 2 : break;
81 2 : case '?':
82 2 : args->error = true;
83 2 : return;
84 : }
85 : }
86 :
87 : // Either read the file list from a file or from the command line.
88 4 : if (file_list_used) {
89 4 : read_file_list_from_file(args, file);
90 : } else {
91 2 : read_file_list_from_argv(args, argc, argv, optind);
92 : }
93 4 : }
|