有没有一种现代C ++的方式来获取已打开文件的
我尝试检查是否有一种方法可以从
FILE*
句柄?我希望避免使用来自<cstdlib>
的std::fopen
,因为有人警告说它可能不安全。我尝试检查是否有一种方法可以从
fstream
中检索FILE*
,但似乎没有这样的方法。FILE*
句柄?我希望避免使用来自<cstdlib>
的std::fopen
,因为有人警告说它可能不安全。fstream
中检索FILE*
,但似乎没有这样的方法。<cstdlib>
中的 std::fopen
,因为有人警告说它可能不安全。
fopen()
并没有什么“不安全”的问题。这是通过 C 标准成为 C++ 标准的一部分。fstream
检索 FILE*
,但似乎没有完全可移植的简单方法。参见像 这样的问题。FILE*
,请使用 C API。namespace file {
template<auto f>
using constant = std::integral_constant< std::decay_t<decltype(f)>, f >;
using file_ptr = std::unique_ptr<std::FILE, constant<std::fclose>>;
FILE* unwrap( file_ptr const& ptr ) { return ptr.get(); }
template<class T> requires (!std::is_same_v< file_ptr, std::decay_t<T> >)
T&& unwrap( T&& t ) { return std::forward<T>(t); }
file_ptr wrap( FILE* ptr ) { return file_ptr(ptr); }
template<class T> requires (!std::is_same_v< file_ptr, std::decay_t<T> >)
T&& wrap( T&& t ) { return std::forward<T>(t); }
template<auto f>
auto call = [](auto&&...args){ return wrap( f( unwrap(decltype(args)(args))... ) ); };
// most FILE* operations can be rebound as follows:
auto open = call<std::fopen>;
auto close = call<std::fclose>;
auto getc = call<std::fgetc>;
auto putc = call<std::fputc>;
// any one that works with raw buffers (like std::fread or std::fwrite) needs more work
}
unique_ptr<FILE,调用fclose的东西>
是一个质量不错的FILE*
C++封装器。
然后我添加了一些机制,将fgetc
和类似函数映射到操作file::file_ptr
的函数上,通过包装/解包装它们。auto pFile = file::open("hello.txt", "r");
实时示例.
auto pFile = file::open("hello.txt", "r");
auto pFileOut = file::open("world.txt", "w");
if (pFile)
{
while(auto c = file::getc(pFile))
{
file::putc(c, pFileOut);
}
}
char*, int
将其映射为std :: span<char>
。
call
助手而不是上面的原始方法会接受混淆参数,将它们映射到C风格参数的元组中,将元组连接在一起并std :: apply C函数。 然后映射返回值。
call
通过一些工作甚至可以具有固定的签名,而不是auto&&...
,因此IDE可以提供提示。
FILE*
是 C 语言的,而不是 C++。C++ 处理文件的方式是使用std::(i|o)fstream
。 - Remy Lebeau