Berkeley SfM
get_path.h
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2015 - Erik Nelson
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  *
18  */
19 
20 #ifndef UTILS_STRINGS_GET_PATH_H
21 #define UTILS_STRINGS_GET_PATH_H
22 
23 #include <string>
24 #include <vector>
25 
26 #include "join_filepath.h"
27 #include "prepend_slash.h"
28 #include "tokenize_file_string.h"
29 
30 namespace strings {
31 
32 // Given a path to a file (e.g. /home/erik/test.png), return the filepath up to
33 // bu not including the last '/'.
34 std::string GetPath(const std::string &path) {
35  // If the input path is empty, return an empty string.
36  if (path.empty())
37  return std::string("");
38 
39  // If the input path ends in a '/', it already does not have a filename.
40  if (path.back() == '/')
41  return path;
42 
43  std::vector<std::string> path_tokens;
44  TokenizeFileString(path, &path_tokens);
45 
46  // If there are no tokens and the path begins with '/', return '/'. Otherwise
47  // the input name is a file and therefore has no path.
48  if (path_tokens.size() == 0)
49  return path[0] == '/' ? std::string("/") : std::string("");
50 
51  // Remove the last token from the tokenized path.
52  path_tokens.erase(path_tokens.end());
53 
54  // Join the remaining tokens, add a prepending slash if one existed in the
55  // input path, and return the result.
56  std::string output_path = JoinFilepath(path_tokens);
57  if (path[0] == '/')
58  return PrependSlash(output_path);
59 
60  return output_path;
61 }
62 
63 } //\namespace strings
64 
65 #endif
std::string GetPath(const std::string &path)
Definition: get_path.h:34
std::string PrependSlash(const std::string &string)
Definition: prepend_slash.h:27
std::string JoinFilepath(const std::vector< std::string > &path_tokens)
Definition: join_filepath.h:49
void TokenizeFileString(const std::string &string, std::vector< std::string > *tokens)