简体   繁体   English

用于windows和unix的文件分隔符

[英]File separator for windows and unix

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 )? 我有一个应该在windows和unix系统上运行的代码(Mac,linux等),我想在相对路径中访问/删除一些文件,有没有办法以一种兼容的方式构建路径两个操作系统(如Java的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 XP或更新的POSIX对此的合规性对我来说已经足够了。

Windows supports a POSIX-compliant path separator. Windows支持符合POSIX的路径分隔符。

This means that you can safely use the forward slash / when building your path and consuming Windows API or C IO functions. 这意味着您可以安全地使用正斜杠/构建路径并使用Windows API或C IO函数。

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. 但是,如果您的代码充当库并公开接受并返回路径的API,则可能必须对输入路径进行posixify并且必须取消返回路径。 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. 即使Windows在命令行上指定路径分隔符时需要\\ ,当在参数CreateFile传递时,您可以使用'/'作为路径分隔符,完全没有问题。

This has been true all the way back to MS-DOS 2.0 (the first to support subdirectories and paths at all). 这一直是MS-DOS 2.0(第一个支持子目录和路径)。 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. 虽然它不会持续很长时间,但是甚至有一些版本的DOS允许你将switchar更改为' - ',所以它允许/甚至在命令行上作为路径分隔符。

除非我遗漏了某些内容,否则Windows中的C库将接受“/”分隔符。

除了其他答案之外,您还可以使用一些C便携式图层库,例如Glib (来自Gtk),它为您提供了一组平台无关的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM