[英]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.