【发布时间】:2016-02-06 12:14:41
【问题描述】:
我必须:
用构造函数定义一个
File_handle类,该类接受一个字符串参数(文件名),在构造函数中打开文件,并在析构函数中关闭它。
据我了解,此类用于提供 RAII,我正在尝试使用 FILE* 作为基本数据结构来实现该类,我的目标基本上是使 FILE* 成为智能指针:
fileHandler.h:
// Class CFile_handler based on FILE*
class CFile_handler {
public:
CFile_handler(); // default constructor
CFile_handler(const std::string& fileName, // constructor
const std::string& mode);
~CFile_handler (); // destructor
// modifying member function
void open_file(const std::string& fileName,
const std::string& mode);
protected:
typedef FILE* ptr;
private:
CFile_handler(const CFile_handler&); // prevent copy creation
CFile_handler& operator= (const CFile_handler&); // prevent copy assignment
ptr c_style_stream; // data member
};
fileHandler.cpp:
// Class CFile_handler member implementations
// default constuctor
CFile_handler::CFile_handler() {
}
// constructor
CFile_handler::CFile_handler(const std::string& fileName, const std::string& mode = "r")
: c_style_stream( fopen( fileName.c_str(), mode.c_str() ) )
{
}
// destructor
CFile_handler::~CFile_handler() {
if (c_style_stream) fclose(c_style_stream);
}
// Modifying member functions
void CFile_handler::open_file(const std::string& fileName, const std::string& mode) {
c_style_stream = ( fopen( fileName.c_str(), mode.c_str() ) );
}
但是,我在重载 I/O operators<< / >> 时遇到了困难,因为我不知道如何实现它们。
如何重载 operator<< 以使该类与 iostream 对象一起使用?
编辑:
正如@LokiAstari 提出的,从istream 继承并定义自己的streambuf 会是更好的策略。
有人可以举例说明处理FILE* 的streambuf 的实现吗?
我要提供的是:
CFile_handler fh("filename.txt", "r");
std::string file_text;
fh >> file_text;
或:
CFile_handler fh("filename.txt", "w");
fh << "write this to file";
【问题讨论】:
-
您需要更具体地了解您想要做什么。您是否尝试将内容放入带有file << 1;?或者您是否尝试将 CFile_handler 本身输出到 iostream 中,例如
std::cout << file? -
@Puppy 是的,我正在尝试实现上述两个操作。我只包含了
operator<<的声明以显示我认为它的外观,以避免“你尝试过什么”的问题。 -
为什么反对票和关闭票?你能添加评论吗?
-
@simplicisveritatis 好吧,通常你不会从标准库继承类,而只是使用它们。我仍然不清楚你想通过
CFile_handler类实现什么。包装FILE*仅在您需要在构造时从您的班级外部传递这些内容时才有意义。 -
如果您希望它与所有现有的流功能一起使用(而不是为所有内容编写自己的运算符istream 派生并在内部定义自己的streambuf处理文件*。