class FileIO { public: // Default constructor. FileIO(); // Set the name of the file. FileIO( std::string filename ); // Close the file if not done so already. ~FileIO(); // Write a string to the file. Can have a new line after written values. void WriteString( std::string string, bool newline ); // Creates/Opens a file to be written and read from. void Open( std::string filename ); // Close the file. void Close(); private: std::string fileName; std::fstream File; }; // Default constructor. FileIO::FileIO() { // Default constructor. } // Set the name of the file. FileIO::FileIO( std::string filename ) { fileName = filename; File.open( filename.c_str() ); } // Close the file if not done so already. FileIO::~FileIO() { // If the file has not been closed yet. if( File.is_open() == true ) { File.close(); } } // Write a string to the file. Can have a new line after written values. void FileIO::WriteString( std::string string, bool newline = false ) { if( File.is_open() == true ) { File << string; if( newline == true ) { File << "\n"; } } } // Creates/Opens a file to be written and read from. void FileIO::Open( std::string filename ) { filename = fileName; File.open( filename.c_str() ); } // Close the file. void FileIO::Close() { // If the file has not been closed yet. if( File.is_open() == true ) { File.close(); } }
I've been trying to create a class to handle file creation, manipulation, etc. Whenever I try to call File.is_open() to check to see if it's 'true', it always returns 'false' ( even if I open the file in the same function as the if statement that checks if it's open ). I'm not sure if I'm doing something stupid at the moment, but it probably has to do with function scope. I want to be able to open the file to read/write to it, and not being able to check if it's open is a problem. I cut out several functions from the class to make it small and to the point, so if you need more examples I can certainly provide.
P.S. I also cut out a bit of debugging and error checking lines, so if you notice those missing don't worry ( unless of course you need to see them ).