C++ file handle - c++

I am trying to implement a file handle class similar to the one in Bjarne Stroustrup's FAQ page. (Scroll to "Why doesn't C++ provide a 'finally' construct".) Unlike his example, however, I want to use C++ file streams instead of a FILE*.
Right now, I am considering creating a FileHandleBase class, or something similarly named, and two derived classes—one for input files and one for output files. Below is the implementation I wrote as a proof-of-concept; keep in mind that it is very simple and unfinished.
class FileHandle {
public:
FileHandle(const char* fn, ios_base::openmode mode = ios_base::in | ios_base::out) {
file.open(fn, mode);
// Check to make sure file is open
}
FileHandle(const string &fn, ios_base::openmode mode = ios_base::in | ios_base::out) {
file.open(fn, mode);
// Check to make sure file is open
}
~FileHandle() {
file.close();
}
private:
fstream file;
};
I would like to know if this is a viable way of making a file handle, that is, whether my inheritance idea is good. I also want to know the best way to deal with the ios_base::openmode parameter because the C++ reference page for std::ifstream says this:
Note that even though ifstream is an input stream, its internal filebuf object may be set to also support output operations.
In what cases would an ifstream be used for output operations, and, similarly, when would an of stream be used for input operations; and should I restrict the options for the ios_base::openmode parameter for my file handle class(es)? That way my input file handle would only handle input operations, and the output version would only handle output operations.

In what cases would an ifstream be used for output operations, and, similarly, when would an ofstream be used for input operations
You would open an output file stream with an std::ios_base::in openmode and vice-versa for an input file stream if you would still like to perform those associated operations using the internal std::filebuf object, which is accessible by stream->rdbuf(). Note that the streams std::ofstream and std::ifstream will still be able to perform output and input respectively even if they are opened with opposite openmodes.
int main() {
std::ofstream stream("test.txt");
stream << "Hello" << std::flush;
stream.close();
stream.open("test.txt", std::ios_base::in);
char buffer[SIZE] = {};
stream.rdbuf()->sgetn(buffer, SIZE);
std::cout << buffer << std::endl;
}

Related

Check if std::fstream is in write or read mode

I need to check whether a std::fstream opened a file in read and/or write mode.
So far, I found iosbase::openmode, but I don't think I can access it.
Is there any other way?
The file streams do not store any information about how they are opened and, correspondingly, can't be queried for the mode they are in. The background is that information isn't needed by the stream implementation itself and it would require to store unnecessary data. Also, when using a stream it is normally clear whether it is read or written: the operations are substantially different that the use indicates which operation is used.
If you really need to get this information, I'd recommend creating a stream type which sets up an std::iostream upon construction using a std::filebuf and stores the information in a pword() so the information can be recovered while passing the stream as std::iostream. The basics could look something like this:
#include <fstream>
#include <iostream>
struct astream_base {
astream_base(std::string const& name, std::ios_base::openmode mode)
: d_sbuf() {
this->d_sbuf.open(name.c_str(), mode);
}
std::filebuf d_sbuf;
};
std::ios_base::openmode mode(std::iostream& stream);
class astream
: private virtual astream_base
, public std::iostream
{
static int index() { static int rc = std::ios_base::xalloc(); return rc; }
public:
astream(std::string const& name, std::ios_base::openmode mode)
: astream_base(name, mode)
, std::ios(&this->d_sbuf)
, std::iostream(&this->d_sbuf) {
this->iword(index()) = mode;
}
friend std::ios_base::openmode mode(std::iostream& stream) {
return std::ios_base::openmode(stream.iword(index()));
}
};
void print_mode(std::iostream& s) {
std::cout << "mode=" << mode(s) << "\n";
}
int main()
{
astream sin("test1", std::ios_base::in);
astream sout("test2", std::ios_base::out);
print_mode(sin);
print_mode(sout);
}
The astream_base is primarily needed to make sure the stream's stream buffer outlives the stream operations. In particular, the stream buffer needs to be alive when the std::ostream's destructor is called as that tries to call pubsync() to flush the stream buffer. Since std::ios is a virtual base of std::istream and std::ostream, the astream_base also needs to be a virtual base.
Other than that, the astream simply associates the used open mode with the std::iostream using an iword(). The function mode() can then be used to determine the value associated. If the stream wasn't open by an astream, the mode will be zero. If you want to support using other streams you could also allow setting the mode() flag which, however, becomes a bit less reliable.
you should set a variable for open mode. check this code:
fstream PatternFile;
ios_base::openmode currentOpenMode = ios_base::out;
strFile.Format(_T("yourFile.txt"));
PatternFile.open(strFile, currentOpenMode);
if(PatternFile.is_open())
{
if(currentOpenMode == ios_base::out)
{
// bingo
}
}

How can the current file be overwritten?

For the following code:
fstream file("file.txt", ios::in):
//some code
//"file" changes here
file.close();
file.clear();
file.open("file.txt", ios::out | ios::trunc);
how can the last three lines be changed so that the current file is not closed, but "re-opened" with everything blanked out?
If I am understanding the question correctly, you'd like to clear all contents of the file without closing it (i.e. set the file size to 0 by setting EOF position). From what I can find the solution you have presented is the most appealing.
Your other option would be to use an OS-specific function to set the end of file, for example SetEndOfFile() on Windows or truncate() on POSIX.
If you're only looking to begin writing at the beginning of the file, Simon's solution works. Using this without setting end of file may leave you in a situation where you have garbage data past the last position you wrote though.
You can rewind the file: put back the put pointer to the beginning of the file, so next time you write something, it will overwrite the content of the file.
For this you can use seekp like this:
fstream file("file.txt", ios::in | ios::out); // Note that you now need
// to open the file for writing
//some code
//"something" changes here
file.seekp(0); // file is now rewinded
Note that it doesn't erase any content. Only if you overwrite it so be careful.
I'm guessing you're trying to avoid passing around the "file.txt" parameter and are trying to implement something like
void rewrite( std::ofstream & f )
{
f.close();
f.clear();
f.open(...); // Reopen the file, but we dont know its filename!
}
However ofstream doesn't provide the filename for the underlying stream, and doesn't provide a way to clear the existing data, so you're kind of out of luck. (It does provide seekp, which will let you position the write cursor back to the beginning of the file, but that wont truncate existing content...)
I'd either just pass the filename to the functions that need it
void rewrite( std::ostream & f, const std::string & filename )
{
f.close();
f.clear();
f.open( filename.c_str(), ios::out );
}
Or package the filestream and filename into a class.
class ReopenableStream
{
public:
std::string filename;
std::ofstream f;
void reopen()
{
f.close();
f.clear();
f.open( filename.c_str(), ios::out );
}
...
};
If you're feeling over zealous you could make ReopenableStream actually behave like a stream, so that you could write reopenable_stream<<foo; rather than reopenable_stream.f<<foo but IMO that seems like overkill.

fstream won't print to file

The following code will print something to a file
std::fstream fout ("D_addr.txt", std::fstream::app);
fout << pkt->Addr() << std::endl;
flush(fout);
fout.close();
While debugging, I watched pkt->Addr() and it has some values. The fout line is passed without problem. Also the file D_addr.txt is created. However after closing the file, the file size is zero! nothing has been written to it.
Where is the problem?
This is not your actual code I guess and if it is I would start with that Addr() function of yours.
Note that fstream::close "closes the file currently associated with the object, disassociating it from the stream. Any pending output sequence is written to the physical file." flush(fout); can be omitted.
You should also specify std::fstream::out flag. "If the function is called with any value in that parameter the default mode is overridden, not combined." So instead of std::fstream::app you should pass std::fstream::app | std::fstream::out.
I'm wondering if you're not using the wrong class. If you want to write to a file, use std::ofstream, and not std::fstream. In particular, the constructor of std::ofstream forces the ios_base::out bit when calling rdbuf()->open; the constructor of std::fstream doesn't (so you're opening the file with neither read nor write access).
And you probably want to check the error status: did the open succeed, and after the close (or the flush), did all of the writes succeed. The usual way of doing this is just:
if ( fout ) {
// All OK...
}
if ( !fout ) {
// Something went wrong.
}
After the open (the constructor), you can use fout.is_open(), which has the advantage of being a little bit more explicit with regards to what you are checking for.
First of all, flush() and fout.close() do not make any harm, but are not needed here, because when fout gets destroyed the file will be closed (and flushed) as part of fstream destructor.
Second, you should use an ofstream or alternatively add the flag std::ios::out to the openmode parameter.
Try something along the lines of:
{
uint64_t x = 42;
std::fstream of("test.txt", std::ios::app);
of << x << std::endl;
}

Fstream fails to create new file

I'm using a FileManager for a project so that reading and writing is less of a hassle for me. Or would be, if I didn't spend all this time debugging it. So, this comfort-class actually caused me stress and time. Awesome.
The problem seems to be the fstream. Before I continue further, here is the structure of my FileManager class.
class FileManager : Utility::Uncopyable
{
public:
FileManager();
void open(std::string const& filename);
void close();
void read(std::string& buffer);
void write(std::string const& data);
private:
std::fstream stream_;
};
Very simple. The buffer is loaded with data during the read function, the data parameter is what's to be written to file. Before reading and writing you must open the file or risk getting a big, fat exception in your face. Kind of like the one I'm getting now.
Scenario: Simple command-line registering of a user, then writing the data to file. I ask for a name and password. The name is copied and appended with .txt (the filename). So it looks like this:
void SessionManager::writeToFile(std::string const& name,
std::string const& password)
{
std::string filename = name + ".txt";
std::string data;
data += name +", " +password;
try
{
fileManager_->open(filename);
fileManager_->write(data);
fileManager_->close();
}
catch(FileException& exception)
{
/* Clean it up. */
std::cerr << exception.what() << "\n";
throw;
}
}
Problem: the open fails. The file is never created, and during the write I get an exception for not having an open file.
FileManager::open() function:
void FileManager::open(std::string const& filename)
{
if(stream_.is_open())
stream_.close();
stream_.open(filename.c_str());
}
and write
void FileManager::write(std::string const& data)
{
if(stream_.is_open())
stream_ << data;
else
throw FileException("Error. No file opened.\n");
}
However, if I create the file beforehand, then it has no troubles opening the file. Yet, when I check, the default std::ios::openmode is std::ios::in | std::ios::out. I can create the file just fine when I only tag std::ios::out, but I want to keep the stream in a read/write state.
How can I accomplish this?
Best method:
void FileManager::open(std::string const& filename)
{
using std::ios_base;
if( stream_.is_open() )
stream_.close();
stream_.open( filename.c_str() ); // ...try existing file
if( !stream_.is_open() ) // ...else, create new file...
stream_.open(filename.c_str(), ios_base::in | ios_base::out | ios_base::trunc);
}
So the code tests for an existing file and, if not, creates it.
You have to call fstream::open with an explicit openmode argument of
ios_base::in | ios_base::out | ios_base::trunc
Otherwise open will fail due to ENOENT.
Table 95 of the draft C++ standard lists possible file open modes and their equivalent in stdio. The default, ios_base::out | ios_base::in is r+. The one I listed above is equivalent to w+. ios_base::out | ios_base::app is equivalent to a. All other combinations involving ios_base::app are invalid.
(At the risk of being scoffed at: you could switch to stdio and use the file mode a+, which reads from the start and appends at the end.)
You cannot use std::ios::in on a non-existing file. Use
std::ios::in | std::ios::out | std::ios::trunc
instead (but make sure it doesn't exist or it will be truncated to zero bytes).
How can I accomplish this?
std::ofstream file("file.txt");
file << data;
Isn't that simpler?
That's the way the library works: std::ios::in | std::ios::out opens it in the equivalent of stdio's "r+", that is it will only open an existing file. I don't believe there's a mode that will do what you are wanting, you'll have to us an OS-specific call or check the file for existence (again, using an OS-specific call) and open it in one mode or the other depending on whether it already exists.
Edit: I assumed that you didn't want the file truncated if it already exists. As other people have noted, if you're happy to truncate any existing file then in | out | trunc is an option.
Just get your function to open
void FileManager::open(std::string const& filename)
{
using std::ios_base;
if(stream_.is_open())
stream_.close();
stream_.open(filename.c_str(), ios_base::in | ios_base::out | ios_base::trunc);
}
if that is the mode you require.
There is no magic way to open a file for read/write creating it if it does not exist but not truncating it (removing its content) if it does. You have to do that in multiple steps.

std::stringstream and std::ios::binary

I want to write to a std::stringstream without any transformation of, say line endings.
I have the following code:
void decrypt(std::istream& input, std::ostream& output)
{
while (input.good())
{
char c = input.get()
c ^= mask;
output.put(c);
if (output.bad())
{
throw std::runtime_error("Output to stream failed.");
}
}
}
The following code works like a charm:
std::ifstream input("foo.enc", std::ios::binary);
std::ofstream output("foo.txt", std::ios::binary);
decrypt(input, output);
If I use a the following code, I run into the std::runtime_error where output is in error state.
std::ifstream input("foo.enc", std::ios::binary);
std::stringstream output(std::ios::binary);
decrypt(input, output);
If I remove the std::ios::binary the decrypt function completes without error, but I end up with CR,CR,LF as line endings.
I am using VS2008 and have not yet tested the code on gcc. Is this the way it supposed to behave or is MS's implementation of std::stringstream broken?
Any ideas how I can get the contents into a std::stringstream in the proper format? I tried putting the contents into a std::string and then using write() and it also had the same result.
AFAIK, the binary flag only applies to fstream, and stringstream never does linefeed conversion, so it is at most useless here.
Moreover, the flags passed to stringstream's ctor should contain in, out or both. In your case, out is necessary (or better yet, use an ostringstream) otherwise, the stream is in not in output mode, which is why writing to it fails.
stringstream ctor's "mode" parameter has a default value of in|out, which explains why things are working properly when you don't pass any argument.
Try to use
std::stringstream output(std::stringstream::out|std::stringstream::binary);