C++流错误未知

C++ fstream error unknown

本文关键字:未知 错误 C++      更新时间:2023-10-16

我正在尝试为一个文件制作一个包装器,所以这是一个fstream的小包装器。我正在制作一些想要读/写二进制和文本到文件的东西,所以我可以让模型加载程序以同样的方式说话。

我有一个问题:当我在ObjLoader.cpp中用这个调用时,为什么我的文件不打开?

Scatterbrain::Log *_file = new Scatterbrain::Log( path, false, true );
    if( ! _file->Works() )
        std::cout << "Error!!";

在散漫的大脑里有这个。h?我确信我已经包含了必要的头,因为一切都编译得很好,所以我认为这一定是我编写文件打开调用的方式的语义问题?-它正在被调用。。

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;
    }
};

简而言之:

  1. 使用成员初始值设定项列表
  2. 不使用new。。。我不知道你为什么会在一开始,也不知道如果是这样,为什么会编译它
  3. 使用operator bool()函数查看它是否"良好"