fstream的相对路径 [英] Relative path for fstream

查看:1680
本文介绍了fstream的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是必须为std :: fstream obj指定绝对路径,还是有一种方法来指定它的相对路径,例如,项目路径?

do I always have to specify absolute path for std::fstream obj or is there a way to specify just relative path to it, like for example, project path?

推荐答案

您也可以使用相对路径。但它们是相对于你调用可执行文件的环境。

You can use relative paths as well. But they are relative to the environment you call your executable from.

这是操作系统相关的,但所有主要系统的行为或多或少相同的AFAIK。

This is OS dependent but all the major systems behave more or less the same AFAIK.

Windows示例:

Windows example:

// File structure:
c:\folder\myprogram.exe
c:\myfile.txt

// Calling command from folder
c:\folder > myprogram.exe

在上面的例子中,你可以访问myfile.txtc:/myfile.txt 或../myfile.txt。如果从根 c:\ 调用myprogram.exe,只有绝对路径可以工作,而是myfile.txt可以工作。

In the above example you could access myfile.txt with "c:/myfile.txt" or "../myfile.txt". If myprogram.exe was called from the root c:\ only the absolute path would work, but instead "myfile.txt" would work.

正如Rob Kennedy在评论中说的,关于fstream的路径真的没什么特别的。但这里是一个使用相对路径的代码示例:

As Rob Kennedy said in the comments there's really nothing special about paths regarding fstream. But here is a code example using a relative path:

#include <fstream>
int main() {
    std::ifstream ifs("../myfile.txt");
    ... // Do something sensible with the file
}

这篇关于fstream的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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