Created
November 6, 2014 17:05
-
-
Save dgodfrey206/4ebcda288a95566ffe2b to your computer and use it in GitHub Desktop.
A facet that holds a stream's filename
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
struct filename_facet : std::locale::facet | |
{ | |
private: | |
std::string m_name; | |
public: | |
filename_facet(std::string const& name, std::size_t refs = 0) | |
: std::locale::facet(refs) | |
, m_name(name) | |
{ } | |
std::string name() const { return m_name; } | |
static std::locale::id id; | |
}; | |
std::locale::id filename_facet::id; | |
std::string fname(std::istream& ifs) | |
{ | |
return std::has_facet<filename_facet>(ifs.getloc()) | |
? std::use_facet<filename_facet>(ifs.getloc()).name() | |
: std::string(); | |
} | |
int main() | |
{ | |
std::ifstream ifs("in.txt"); | |
ifs.imbue(std::locale(ifs.getloc(), new filename_facet("in.txt"))); | |
std::cout << fname(ifs); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment