[英]C++ fstream error unknown
我正在尝试为文件创建包装器-以便fstream的小包装器。 我正在做一些想将二进制和文本读/写到文件的事情,因此我可以使模型加载器以相同的方式进行交谈。
我有一个问题:为什么在ObjLoader.cpp中调用此文件时,为什么我的文件没有打开?
Scatterbrain::Log *_file = new Scatterbrain::Log( path, false, true );
if( ! _file->Works() )
std::cout << "Error!!";
在scatterbrain.h中有这个吗? 我确定我已经包含了必要的标头,因为一切都可以正常编译,所以我认为这与我编写文件open调用的方式必然是语义问题吗? -被叫了
namespace Scatterbrain
{
class Log
{
private:
std::string name;
bool rOnly;
bool isBinary;
int numBytes;
std::fstream file;
protected:
virtual int SizeBytes() { numBytes = (file) ? (int) file->tellg() : 0; return numBytes; }
public:
Log(){}
Log( std::string filename, bool append, bool readOnly )
{
if(FileExists(filename))
{
name = filename;
rOnly = readOnly;
file.open( name.c_str(), ((readOnly) ? int(std::ios::out) : int(std::ios::in |std::ios::out)) | ((append) ? int(std::ios::app) : int(std::ios::trunc)) );
}
}
virtual bool Works() { return (file.is_open() && file.good() ); }
谢谢
关于这一切,可以说很多,所以我将其放在评论中:
class Log
{
private:
std::string name;
bool rOnly;
std::fstream file;
public:
Log(){}
Log( std::string filename, bool append, bool readOnly)
: name(filename), // Use initializer lists
rOnly(readOnly),
file(filename, (readOnly ? std::ios::out : std::ios::in | std::ios::out) |
(append ? std::ios::app : std::ios::trunc))
{
// Why check if the file exists? Just try to open it...
// Unless, of course, you want to prevent people from creating
// new log files.
}
virtual bool Works()
{
// Just use the fstream's operator bool() to check if it's good
return file;
}
};
简而言之:
new
...我不知道您为什么要放在第一位,或者为什么要编译它。 operator bool()
函数查看其是否“良好”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.