|
| 1 | +/* |
| 2 | + * FastBasic - Fast basic interpreter for the Atari 8-bit computers |
| 3 | + * Copyright (C) 2017-2020 Daniel Serpell |
| 4 | + * |
| 5 | + * This program is free software; you can redistribute it and/or modify |
| 6 | + * it under the terms of the GNU General Public License as published by |
| 7 | + * the Free Software Foundation, either version 2 of the License, or |
| 8 | + * (at your option) any later version. |
| 9 | + * |
| 10 | + * This program is distributed in the hope that it will be useful, |
| 11 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | + * GNU General Public License for more details. |
| 14 | + * |
| 15 | + * You should have received a copy of the GNU General Public License along |
| 16 | + * with this program. If not, see <http://www.gnu.org/licenses/> |
| 17 | + */ |
| 18 | + |
| 19 | +// ifile.cc: Opens included file |
| 20 | + |
| 21 | +#include "ifile.h" |
| 22 | +#include <fstream> |
| 23 | + |
| 24 | +static std::string get_path(std::string fname) |
| 25 | +{ |
| 26 | + // Get's path to file. This understands either '/' or '\' as path |
| 27 | + // separators, to be compatible between Unix and Windows. |
| 28 | + auto p = fname.find_last_of("/\\"); |
| 29 | + if( p != fname.npos ) |
| 30 | + return fname.substr(0, p); |
| 31 | + else |
| 32 | + return std::string(); |
| 33 | +} |
| 34 | + |
| 35 | + |
| 36 | +std::unique_ptr<std::istream> open_include_file(std::string current_file, std::string fname) |
| 37 | +{ |
| 38 | + auto f = std::make_unique<std::ifstream>(); |
| 39 | + |
| 40 | + // Get path of current file |
| 41 | + std::string path = get_path(current_file); |
| 42 | + |
| 43 | + if( !path.empty() ) |
| 44 | + path = path + "/" + fname; |
| 45 | + else |
| 46 | + path = fname; |
| 47 | + |
| 48 | + // Tries to open |
| 49 | + f->open(path, std::ios::binary); |
| 50 | + if( f->is_open() ) |
| 51 | + return f; |
| 52 | + |
| 53 | + // Try again without path |
| 54 | + f->open(fname, std::ios::binary); |
| 55 | + if( f->is_open() ) |
| 56 | + return f; |
| 57 | + |
| 58 | + f.reset(); |
| 59 | + return f; |
| 60 | +} |
0 commit comments