I have a code that should run on both windows and unix systems (Mac, linux etc.) and I want to access / delete some files in a relative path, is there a way to construct the path in a way that will be compatible for both OSs (like Java's File.separator
)?
The closest thing that I though about is something like that:
#ifdef _WIN32
#define FILE_SEPARATOR "\\"
#else
#define FILE_SEPARATOR "/"
#endif
//in windows - ".\\filedir\\filename.txt"
//in *nix - "./filedir/filename.txt"
const char * mypath = "." FILE_SEPARATOR "filedir" FILE_SEPARATOR "filename.txt";
EDIT
After reading the answers / comments below - I would like to add that a confirmation that windows XP or newer compliance with POSIX regarding this is enough for me.
Windows supports a POSIX-compliant path separator.
This means that you can safely use the forward slash /
when building your path and consuming Windows API or C IO functions.
However, if your code acts as a library and exposes an API which accepts and returns paths, you may have to posixify input paths and unposixify return paths. This will add a slight burden but will feel more native to your consumers.
The simple answer is to just use /
on both. Even though Windows requires \
when you're specifying a path separator on the command line, when passed in an argument CreateFile
, you can use '/' as the path separator with no problems at all.
This has been true all the way back to MS-DOS 2.0 (the first to support subdirectories and paths at all). Though it didn't last very long, there were even versions of DOS that allowed you to change the switchar
to '-', so it allowed /
as the path separator even on the command line.
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