Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an idiom for adding a trailing slash to a file path?

Tags:

c++

c

linux

I have a program that takes a folder path as a command line argument. And then I concatenate that with filenames to access those files.

For example, folder_path is "./config/" and then file_path would be "./config/app.conf" as shown below

stringstream ss;
ss << folder_path << "app.conf";
file_path = ss.str();

But this wouldn't work if folder_path doesn't contain an ending slash. It seems like a common issue, so I was wondering if there's an idiom for adding the slash at the end if it doesn't exist.

like image 464
UXkQEZ7 Avatar asked Aug 03 '13 00:08

UXkQEZ7


2 Answers

I usually do this, if the path is in an std::string named pathname:

if (!pathname.empty() && *pathname.rbegin() != '/')
    pathname += '/';

Or, with basic_string::back():

if (!pathname.empty() && pathname.back() != '/')
    pathname += '/';

Add a case for backslash if necessary.

Added: Also note that *nix will handle consecutive slashes in path names as a single slash. So in many situations, it's sufficient to just always add a slash without checking.

like image 158
Jason C Avatar answered Sep 22 '22 07:09

Jason C


Linux wont care if you have an extra slash, so /home/user/hello and /home/user//hello are the same location. You could add the slash as a failsafe. Or, you could check for it, by checking the last character.

like image 35
phyrrus9 Avatar answered Sep 24 '22 07:09

phyrrus9