c++ filestream problems when opening file in read write mode - c++

Consider the following code snippet:
const char * filePath = "C:/blah.mtt";
fstream fs(filePath, ios::in | ios::out | ios::binary);
if (fs.fail())
std::cout << "Failed to open the file!\n";
the fs.fail() check succeeds always. Does it mean that I can't open a file in both read write mode at the same time?
Creating an empty file first and then running the above code, fs.fail() is false always. What is the rational for such a behavior by the fstream class?
Note: I do have requisite permissions for creating the file. I am trying this on windows 10 using VS2015

Does it mean that I can't open a file in both read write mode at the same time?
No, you can do this, but the question is whether you can create a file by doing so.
Generally you'll need to add the trunc flag (ironically one of the options for how to handle an existing file), or remove the in flag (see here).
Yes, this is a bit of a pain, but it comes from how the original POSIX APIs work. Blame them!
Creating an empty file first and then running the above code, fs.fail() is false always. What is the rational for such a behavior by the fstream class?
You can always open a file that exists (well, subject to permissions). That behaviour makes sense.

the fs.fail() check succeeds always. Does it mean that I can't open a file in both read write mode at the same time?
Refer to #Lightness Races in Orbit's answer for a better explanation.
Creating an empty file first and then running the above code, fs.fail() is false always. What is the rational for such a behavior by the fstream class?
If you look at the constructor definition of fstream you can see that mode defines the way you open it. It has other options like app to append to an existing file. If you open up a file using the following code:
fstream fs(filePath, ios::in | ios::out | ios::binary);
You are saying create a new file if it doesn't exist. Which fails if you pre-created it. You should add the app, ate or truncflag if you want it to open successfully. This depends on what exactly you want to do. However, do note that in between the steps of creating and then opening it doesn't guarantee that the file is still there. You should try to do it in one swoop and let exception handling do its work, since you can never go around the errors anyway.

Related

Can't access the file(Internal File Buffer NULL)

I have this strange bug. I have a program which writes text to the file using the fstream, but the file is not being created and therefore no text is appended. When I debug my code, it shows me this:
create_new_file = {_Filebuffer={_Pcvt=0x0000000000000000 <NULL> _Mychar=0 '\0' _Wrotesome=false ...} }.
But whenever I use ofstream everything works.
Here is the code:
std::fstream create_new_file{ fileName.str()};
std::unique_ptr<std::string> changes = std::make_unique<std::string>("");
std::cin >> *changes;
create_new_file << *changes << "\n";
Here is the code which works:
std::ofstream create_new_file{ fileName.str()};
I have seen a similar post on Stack Overflow but the answer did not resolve my issue. I have tried adding the std::ios::trunc to the fstream but that did not help. But whenever I use ofstream everything works just as expected.
The problem is that for bidirectional file streams the trunc flag must always be explicitly specified, i.e., if you want the file content to be discarded then you must write in | out | trunc as the second argument as shown below.
Thus, to solve the problem change std::fstream create_new_file{ fileName.str()}; to :
//-------------------------------------------------------------------------vvvvvvvvvvvvvvv---->explicitly use trunc
std::fstream create_new_file{ "output.txt", ios_base::in | ios_base::out | ios_base::trunc};
Working demo
This file stream buffer open reference is useful. It shows a table with the different modes and what happens when they are used.
When you open a std::fstream the default mode for the constructor is in | out. If we look that up in the table we see that this will fail if the file doesn't exist.
And you never check for failure (which you always should do).
If you only want to write to the file then use std::ofstream as it will open the files in out mode, which creates the file if it doesn't exist.
If you want to only append to the file, still use std::ofstream but use the mode out | app, which will create the file and make sure all output is appended (written to the end).

preferred c++ i/o stream method: fstream or ifstream/ofstream or something else entirely?

I have created a roster program that accepts user input to create/write/delete information into and out of a specified text file. My issue now becomes wanting to create a lasting text file that isn't overwritten every time I re-run the program and am not sure if using fstream or a combination of of/ifstream is better practice, or if there is maybe a third option I missed when checking the reference docs.
Right now I am simply using: std::ofstream outfile("roster.txt"); which works, until I kill and re-run the program to which my text file is now wiped clean.
check out the append flag. it writes to the end of an existing file.
http://www.cplusplus.com/doc/tutorial/files/
example here.
std::ofstream outfile("roster.txt" , ios::app)

Default mode of fstream

I was looking at the SO post C++ file stream open modes ambiguity. I wanted to know the default file opening mode of fstream. One of the answer says,
What the above implies is that the following code opens the file with
exactly the same open flags fstream f("a.txt", ios_base::in |
ios_base::out); ifstream g("a.txt", ios_base::out); ofstream
h("a.txt", ios_base::in);
So if I understand correctly, in case I create object of fstream, I should be able to either read or write.
But below code does not write any data to file
fstream testFile1;
testFile1.open("text1.txt");
testFile1<<"Writing data to file";
testFile1.close();
However adding mode as given below creates text file with data "Writing data to file"
testFile1.open("text1.txt", ios::out);
So whether the default mode is implementation defined? I am using TDM-GCC-64 toolchain.
The default mode for std::fstreams is std::ios::in|std::ios::out. (Source)
The reason your code doesn't print anything to test1.txt is that the std::ios::in|std::ios::out mode does not create the file if it does not already exist (Source: table on this page).
You can use the std::ios::in|std::ios::app mode, which will start reading from the start, will start writing from the end, and will create the file if it does not exist. Note that using app mode, the file will seek to the end before each write (Source).
The default mode of ifstream is in. The default mode of ofstream is out. That's why they're named that way. fstream has no default mode.
Your example only shows the two defaults, and it shows that by omission of explicit arguments. That fstream f("a.txt", ios_base::in | ios_base::out) uses two explicit arguments is precisely because there is no default mode.

C++ ofstream equivalent to Win32 CreateFile with CREATE_NEW

In an application I want to be sure that I am writing a brand new (binary) file. In Win32 programming I know I can do this with CreateFile using CREATE_NEW, but I can't work out a pure C++ standard way.
Creates a new file, only if it does not already exist.
If the specified file exists, the function fails and the last-error code is set to ERROR_FILE_EXISTS (80).
If the specified file does not exist and is a valid path to a writable location, a new file is created.
I tried using std::ios::out | std::ios::binary | std::ios::ate then seeing if tellp gave me the start of the file or not, but apart from the obvious case that this would still overwrite an empty file, it also seems to truncate a non-empty file anyway as if I used std::ios::trunc...
This was on VS2013, although I assume this is not a compiler/library bug.
The C++ standard doesn't have an API guaranteeing a new file. When opening an existing file in write-only mode without specifying std::ios_base::app it is truncated (independent on whether std::ios_base::trunc is used). I don't know about Windows but on POSIX this would retain the original inode and processes already having opened the file can still access it.
If it is sufficient to get an open and empty file rather than a new one, omiting std::ios_base::in and std::ios_base::app should do the trick (note that opening an std::fstream or an std::ifstream implicitly adds std::ios_base::in).

c++ overwrite already opened file

I am opening a file with ifstream to check if it exists. Then I close it and open it with ofstream to write to it, and I think setting ios::trunc flag allows me to overwrite it.
However I'd like the ability to keep the file open if it exists, but I used an ifstream to open it so does that mean I can't write to the file till I close and re-open using fstream or ofstream? I didn't use fstream to begin with because that wouldn't tell me if the file was already there or not.
Just open a read-write fstream on the file. You can test if the file previously existed (and was non-empty) by seeking to the end and seeing if you're at a non-zero offset. If so, the file existed, and you can do whatever with it. If not, the file didn't exist or was empty. Assuming you don't need to distinguish between those two cases, you can then proceed as if it did not exist.
For example:
// Error checking omitted for expository purposes
std::fstream f("file.txt", std::ios::in | std::ios::out);
f.seekg(0, std::ios::end)
bool didFileExist = (f.tellg() > 0);
f.seekg(0, std::ios::beg);
// Now use the file in read-write mode. If didFileExist is true, then the
// file previously existed (and has not yet been modified)
The setting ios::trunc erases previous contents of the file.
Try opening the file without this setting; with only the 'write' setting.
this is touching very serios problem - race conditions - what if somebody manages to do something with this file between closing and reopening? unfortunately iostream does not provide any means of resolving that issue - you can use cstdio FILE. If you want to turncate file if exists or create new one if not use fopen(name, "w"). If you want to turncate file if it exists or fail otherwise, then it seems standard library has nothing to offer, and you should go to other libraries or platform specific functions like OpenFile in windows.h