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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With