如何使用带有相对路径的fstream对象? [英] How to use fstream objects with relative path?

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

问题描述

我是否总是必须为从 std :: fstream 类实例化的对象指定绝对路径?换句话说,有没有办法只指定相对路径,例如项目路径?

Do I always have to specify absolute path for objects instantiated from std::fstream class? In other words, is there a way to specify just relative path to them such as 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

在上面的示例中,您可以使用 c:/myfile.txt访问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天全站免登陆