开发者

How get file path from std::ifstream in c++

开发者 https://www.devze.com 2023-01-03 07:35 出处:网络
I open a file using std::ifstream. I may open file using relative path (file.txt) or absolute path (C:\\test\\file.txt).

I open a file using std::ifstream.

I may open file using relative path (file.txt) or absolute path (C:\test\file.txt).

As I am passing a string as the file name, I dont know whether it is relative or absolute path.

Can anybody tell me how to get absolute path after file has been successfully open using std::ifstream ?

e.g.:

std::ifstream file(strFile); // strFile is "file.txt" or "C:\test\file.txt"

I want to get the absolute path after the file was open successfully.

Thank开发者_运维知识库s,


You can't, std::ifstream does not store this information.

What you can do, however, is:

  1. use process' current working directory to compose the absolute path yourself, or
  2. use a library like Boost.Filesystem library to transform between relative and absolute paths.

    boost::filesystem::path abs_path = boost::filesystem::complete("./rel/path");
    std::string abs_path_str = abs_path.string();
    


The fstream classes have no functionality for accessing or processing the name used to open the file with, and the C++ Standard Library has no filename processing functions - you will have to write the code yourself, or use a third-party library or operating system-supplied functions.


I don't think it is possible for a std::fstream. I did it for a FILE * on Windows (in a non-portable way). See from file object to file name.

Have you considered extending the ifstream with your own class that remembers the file name?

0

精彩评论

暂无评论...
验证码 换一张
取 消