请参考C ++项目中的数据文件 [英] Refer to data files from within C++ project

查看:115
本文介绍了请参考C ++项目中的数据文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++项目,文件夹结构如下:

I have a C++ project with a folder structure something like so:

root/trunk
root/trunk/src/...        
root/trunk/include/...    
root/trunk/utils/...      <-- this has the `main` programs which are compiled
root/trunk/bin/...        compiled binaries
root/data/...             data used in the programs


b $ b

在我的源文件中,我有时引用包含在数据子文件夹中的文件。我希望我使用的路径是相对路径(因为我与其他人共享此项目)。

In my source files, I sometimes refer to files included in the data subfolders. I want the paths I use to be relative paths (because I am sharing this project with someone else).

如何确保始终可以找到数据文件?目前我使用以下路径:

How can I ensure that the data files can always be found? Currently I use paths such as the following:

std::string my_data("../../../data/path/to/file.txt");

但是,我发现很难使用它来计算相对路径的位置,当源文件被移动时。

However, I find it difficult using this to work out where the relative path leads to, and can be messy when source files are moved. Is the a better way of accomplishing the same thing?

推荐答案

组织数据文件的常用方法是建立一个数据根文件夹在程序启动,然后编码您的路径相对于。可以通过搜索(特别命名的文件或目录(例如.foo))并由环境变量覆盖来自动确定数据根目录(通过搜索(当前目录及其父目录,祖父目录等,直到真实根目录)或命令行开关(例如FOO_DATA_DIR =/ home / fred / bar)。

A common method of organizing data files is to establish a "data root" folder at program startup, and then code your paths relative to that. The data root can be automatically determined by searching (the current directory and perhaps its parent, grandparent, etc, up to the real root.) for a specially named file or directory (eg ".foo"), and overridden by an environment variable or command-line switch (eg FOO_DATA_DIR="/home/fred/bar").

为方便起见,程序可以将其当前工作目录更改为数据根目录,或者,您可以在用户界中以编程方式解析数据根相对路径。

For conveniance the program could change its current working directory to the data root, or alternatively you can resolve your data root relative paths programmatically in userland.

这篇关于请参考C ++项目中的数据文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆