I need to be able to create a non-existent file. The design is as follows : I have 1 thread for all file IO, and in the data structure that encapsulates the file, I have a std::fstream file_handle.
Can I create and open this file in the mode - std::fstream::in | std::fstream::out | std::fstream::app
?
I need this because I have to use this one handle to do both - reads, and writes to the end of the file.
However this is not creating the file. Here's what I have :
class file_io
{
std::string filename;
std::fstream file_handle;
file_io(std::string name)
{
filename = name;
}
void open_file()
{
if(!file_handle.is_open())
{
file_handle.open(filename.c_str(), std::fstream::in | std::fstream::out | std::fstream::app);
if(!file_handle.is_open())
{
std::cout << "Could not open file " << filename ;
}
else
{
std::cout << "successfully opened file " << filename;
}
}
}
~file_io()
{
if(file_handle.is_open)
file_handle.close();
}
};
I call onto open_file each time I need to write into end of the file, or read the file contents. But the file does not get created. Can anyone please help me understand what I am doing wrong here, and what the right approach is to solve my problem?
Also, if the only alternative is to have to different file handles, one for append(need to create here as well) and one for reads, is it okay if I read the file while the file handle for append is still open? Also, what should the mode of opening be for create if non-existent and append ?