I've been working with c++ and I noticed that whenever I use .open()
for a file if there's no file with that name, it just creates one. Is there a way to have it not do this?
Asked
Active
Viewed 90 times
0

MmMm SsSs
- 87
- 7
-
try to read the file first to see if its there – pm100 Apr 08 '22 at 00:14
-
Does this answer your question? [Fastest way to check if a file exists using standard C++/C++11,14,17/C?](https://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exists-using-standard-c-c11-14-17-c) – Christian Apr 08 '22 at 00:22
-
[I find this chart form the C++ Standard helpful](http://eel.is/c++draft/file.streams#tab:filebuf.open.modes). I can then [map it to this table](https://en.cppreference.com/w/c/io/fopen#File_access_flags) to see what'll happen. If we open a file for `"r+"` which is an `ofsteam` opened with `ios::in`, the file will not open and will not be created. – user4581301 Apr 08 '22 at 01:00
1 Answers
2
Check if the file exists first. The following link might help you:
Fastest way to check if a file exists using standard C++/C++11,14,17/C?
Or maybe, you could use the nocreate option:
void open(const char *filename, ios::openmode mode); where,
- First argument *filename specifies the name of file and location.
- Second argument open() member function defines the mode in which the file should be opened.
All the options here: https://www.tutorialride.com/cpp/file-handling-in-c.htm
-
2Checking if the file already exists before trying to open it is not reliable, the file might have been deleted or moved between the moment you check and when you try to open it. – François Andrieux Apr 08 '22 at 01:01
-
I recommend expanding on this answer to demonstrate which open modes will not create a new file. I've linked a few helpful tables above in the comments you can feel free to reference. – user4581301 Apr 08 '22 at 01:18