在C程序中抽象文件系统的方法
我正在 SDL 中启动一个程序,它显然需要加载文件系统的资源。 我希望程序内的文件调用与平台无关。我最初的想法是定义一个基于系统类型在预处理器中定义的宏(让我们称之为路径的 PTH),然后使用它在程序中进行文件调用。 例如,
SDL_LoadBMP(PTH("data","images","filename"));
将简单地转换为与文件系统相关的内容。
如果宏是执行此操作的可接受方法,那么此类宏会是什么样子(我如何检查正在使用哪个系统,在宏中连接字符串?)
如果不是,那么执行此操作的可接受方法是什么?
I'm starting out a program in SDL which obviously needs to load resources for the filesystem.
I'd like file calls within the program to be platform-independent. My initial idea is to define a macro (lets call it PTH for path) that is defined in the preprocessor based on system type and and then make file calls in the program using it.
For example
SDL_LoadBMP(PTH("data","images","filename"));
would simply translate to something filesystem-relevant.
If macros are the accepted way of doing this, what would such macros look like (how can I check for which system is in use, concatenate strings in the macro?)
If not, what is the accepted way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Boost Filesystem 模块可能是您最好的选择。它覆盖了路径上的“/”运算符,因此您可以执行以下操作:
The Boost Filesystem module is probably your best bet. It has override for the "/" operator on paths so you can do stuff like...
GLib 有许多可移植的路径操作函数。 如果您更喜欢 C++,还有 boost::filesystem。
GLib has a number of portable path-manipulation functions. If you prefer C++, there's also boost::filesystem.
没有必要将其作为宏。
一种常见的方法是抽象路径以使用正斜杠作为分隔符,因为这(几乎是偶然的!)很好地映射到大部分实际平台。对于那些没有的地方,您只需在文件系统实现层内进行转换即可。
There's no need to have this as a macro.
One common approach is to abstract paths to use the forward slash as a separator, since that (almost accidentally!) maps very well to a large proportion of actual platforms. For those where it doesn't, you simply translate inside your file system implementation layer.
查看 OS9 os.path.join (macpath) 的 python 实现,
我不熟悉在旧 Mac 上使用 SDL 进行开发。游戏资源的另一种选择是使用包文件格式,并将资源直接加载到内存中(例如地图 < string, SDL_Surface > ),
从而加载一个文件(甚至可能是一个 zip,在加载时解压缩)
Looking at the python implementation for OS9 os.path.join (macpath)
I'm not familiar with developing under SDL on older Macs. Another alternative in game resources is to use a package file format, and load the resources into memory directly (such as a map < string, SDL_Surface > )
Thereby you would load one file (perhaps even a zip, unzipped at load time)
我只需在程序的启动代码中执行平台等效版本的
chdir(data_base_dir);
,然后使用"images/filename"
形式的相对 unix 样式路径。最后一个不支持此功能的系统是 MacOS 9,现在完全不相关了。I would simply do the platform-equivalent version of
chdir(data_base_dir);
in your program's startup code, then use relative unix-style paths of the form"images/filename"
. The last systems where this would not work were MacOS 9, which is completely irrelevant now.