How to Build a Full Path String (Safely) from Separate Strings

How to build a full path string (safely) from separate strings?

Check out QDir for that:

QString path = QDir(dirPath).filePath(fileName);

How to split a path into separate strings?

Indeed, there is path_iterator. But if you want elegance:

#include <boost/filesystem.hpp>

int main() {
for(auto& part : boost::filesystem::path("/tmp/foo.txt"))
std::cout << part << "\n";
}

Prints:

"/"
"tmp"
"foo.txt"

And

    for(auto& part : boost::filesystem::path("/tmp/foo.txt"))
std::cout << part.c_str() << "\n";

prints

/
tmp
foo.txt

No need to worry about the moving parts

Building a path from strings in C

Character constants such as PATH_SEP are not automatically NUL-terminated. When you call

strcat(buffer, PATH_SEP);

the strcat routine expects both arguments to point to NUL-terminated strings. Because PATH_SEP isn't NUL terminated the routine continues scanning memory, looking for a NUL byte. Eventually it either overwrites something important or access memory it shouldn't.

Change

char *PATH_SEP = '\\';

to

char *PATH_SEP = "\\";

and your code should perform as expected.

Best of luck.

What's the correct way to build up a file path from multiple strings?

I think the best way of building filesystem path is to use Path.Combine, even for string literals.

var path = Path.Combine("ABCD", "Node1", "Node2", "Node3");

Anyway, paths containing both "\" and "/" should work correctly, but canonical way is of course Path.Combine.

c++ combine path of file as a string with file name

You would use something like:

string path ("yourFilePath");
string filename ("filename");

You could then open the file like this:

ifstream inputFileStream;
inputFileStream.open(path + fileName);

Depending on your requirements, you will have to decide whether to use formatted or unformatted input when reading. I would read this for more information regarding that.

Cocatenation referenced from: C++ string concatenation
Reading referenced from: C++ read and write with files

Build the full path filename in Python

This works fine:

os.path.join(dir_name, base_filename + '.' + filename_suffix)

Keep in mind that os.path.join() exists only because different operating systems use different path separator characters. It smooths over that difference so cross-platform code doesn't have to be cluttered with special cases for each OS. There is no need to do this for file name "extensions" (see footnote) because they are always preceded by a dot character, on every OS.

If using a function anyway makes you feel better (and you like needlessly complicating your code), you can do this:

os.path.join(dir_name, '.'.join((base_filename, filename_suffix)))

If you prefer to keep your code clean, simply include the dot in the suffix:

suffix = '.pdf'
os.path.join(dir_name, base_filename + suffix)

That approach also happens to be compatible with the suffix conventions in pathlib, which was introduced in python 3.4 a few years after this question was asked. New code that doesn't require backward compatibility can do this:

suffix = '.pdf'
pathlib.PurePath(dir_name, base_filename + suffix)

You might be tempted to use the shorter Path() instead of PurePath() if you're only handling paths for the local OS. I would question that choice, given the cross-platform issues behind the original question.

Warning: Do not use pathlib's with_suffix() for this purpose. That method will corrupt base_filename if it ever contains a dot.


Footnote: Outside of Micorsoft operating systems, there is no such thing as a file name "extension". Its presence on Windows comes from MS-DOS and FAT, which borrowed it from CP/M, which has been dead for decades. That dot-plus-three-letters that many of us are accustomed to seeing is just part of the file name on every other modern OS, where it has no built-in meaning.

Create a Path from String in Java7

You can just use the Paths class:

Path path = Paths.get(textPath);

... assuming you want to use the default file system, of course.

Joining paths in Java

Even though the original solution for getting the current directory using the empty String works. But is recommended to use the user.dir property for current directory and user.home for home directory.

Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(), "data", "foo.txt");
System.out.println(filePath.toString());

output:

/Users/user/coding/data/foo.txt

From Java Path class Documentation:

A Path is considered to be an empty path if it consists solely of one name element that is empty. Accessing a file using an empty path is equivalent to accessing the default directory of the file system.


Why Paths.get("").toAbsolutePath() works

When an empty string is passed to the Paths.get(""), the returned Path object contains empty path. But when we call Path.toAbsolutePath(), it checks whether path length is greater than zero, otherwise it uses user.dir system property and return the current path.

Here is the code for Unix file system implementation: UnixPath.toAbsolutePath()


Basically you need to create the Path instance again once you resolve the current directory path.

Also I would suggest using File.separatorChar for platform independent code.

Path currentRelativePath = Paths.get("");
Path currentDir = currentRelativePath.toAbsolutePath(); // <-- Get the Path and use resolve on it.
String filename = "data" + File.separatorChar + "foo.txt";
Path filepath = currentDir.resolve(filename);

// "data/foo.txt"
System.out.println(filepath);

Output:

/Users/user/coding/data/foo.txt


Related Topics



Leave a reply



Submit