Is it possible to open an fstream on a file that does not exist with both ios::in & ios::out without getting an error?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
If an error occurs the message is displayed and one (1) is returned. However it is possible to compile and execute just
ofstream out("test", ios::out);
andifstream in("test", ios::in);
without any errors. Either way the file test is created.I haven't checked to guarantee that it will open without error, but I feel pretty confident that it should.
This code will print
1
and will not create "test.txt" file, if it does not exit. So it is not possible to open and fstream on a file that does not exist without getting an error.To open an
fstream
on a file that does not exist for input and output (random access) without getting an error, you should provide the flagsfstream::in | fstream::out | fstream::trunc
in theopen
(or constructor) call. Since the file does not already exist, truncating the file at zero bytes is no drama.You may want an error when opening a file that doesn't exist when specifying only
ios::in
since you'll never be able to read from the stream so failing early in this case will prevent surprise failures later on.