简体   繁体   中英

C++ fstream error unknown

I'm trying to make a wrapper for a file - so a small wrapper to fstream. I am in the process of making something that will want to read/write binary and text to file, so I can make model loaders talk in the same way.

I've one question: Why doesn't my file open when I call with this in ObjLoader.cpp ?

Scatterbrain::Log *_file = new Scatterbrain::Log( path, false, true );

    if( ! _file->Works() )
        std::cout << "Error!!";

Having this in scatterbrain.h ? I'm sure I've included the necessary headers as everything compiles fine, so I figure it must be a semantic problem with the way I wrote the file open call? - it is getting called..

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

Thanks

There's a lot that could be said about this all, so I'll just put it in comments:

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

In short:

  1. Use member initializer lists
  2. Don't use new ... I have no idea why you were in the first place, or why it compiled if it did.
  3. Use the operator bool() function to see if it's "good" or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM