fstream in and out on nonexistent file

2020-04-02 08:22发布

Is it possible to open an fstream on a file that does not exist with both ios::in & ios::out without getting an error?

标签: c++ fstream
4条回答
forever°为你锁心
2楼-- · 2020-04-02 09:02
#include <fstream> 

ofstream out("test", ios::out);
if(!out)
{
    cout << "Error opening file.\n";
    return 1;
}

ifstream in("test", ios::in);
if(!in)
{
    cout << "Error opening file.\n";
    return 1;
}

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); and ifstream in("test", ios::in); without any errors. Either way the file test is created.

查看更多
神经病院院长
3楼-- · 2020-04-02 09:11
std::fstream f("test.txt", std::ios_base::out);
f.close(); //file now exists always
f.open("test.txt", fstream::in | std::ios_base::out);
//f is open for read and write without error

I haven't checked to guarantee that it will open without error, but I feel pretty confident that it should.

查看更多
Explosion°爆炸
4楼-- · 2020-04-02 09:14
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  fstream f("test.txt", fstream::in | fstream::out);
  cout << f.fail() << endl;
  f << "hello" << endl;
  f.close();    
  return 0;
}

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.

查看更多
够拽才男人
5楼-- · 2020-04-02 09:15

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 flags fstream::in | fstream::out | fstream::trunc in the open (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.

查看更多
登录 后发表回答