Reputation: 43447
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.
Upvotes: 2
Views: 4721
Reputation: 400334
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)
Upvotes: 2
Reputation: 6181
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
Upvotes: 0
Reputation: 57718
The setting ios::trunc
erases previous contents of the file.
Try opening the file without this setting; with only the 'write' setting.
Upvotes: 1