2014-09-04 82 views
1

我想在append模式下打开文件,但如果文件已存在,请覆盖其内容。以追加模式打开文件,但截断文件

我已经试过这样的事情,但是这是不行的(我没有用太多的经验|和&运营商,因为你可以看到):

//does nothing 
_fs.open(_path, std::ios_base::out | std::ios_base::app | std::ios_base::trunc); 

然后,我决定开文件中out模式,然后再次打开,但它append模式之前关闭它,但当然,这似乎是一个不好的编程方式来做到这一点:

if(fexists(_path.c_str())){//Checks if the file exists 
    _fs.open(_path, std::ios::out);//Overrides the contents 
    _fs.close(); 
} 

_fs.open(_path, std::ios_base::out | std::ios_base::app); 

然后凭直觉我写了这样的事情:

_fs.open(_path, std::ios_base::out | std::ios_base::app & std::ios_base::out | std::ios_base::trunc); 

现在它工作,为什么?

+1

你为什么要附加一个文件,如果你只是打算无论如何要删除它,那就是截断点模式。另外,你不能在'std :: ios :: app'和'std :: ios :: trunc'模式下打开一个文件 – Kevin 2014-09-04 16:28:02

回答

2

它的工作原理,因为

std::ios_base::out | std::ios_base::app & std::ios_base::out | std::ios_base::trunc 

==

std::ios_base::out | (std::ios_base::app & std::ios_base::out) | std::ios_base::trunc 

==

std::ios_base::out | 0 | std::ios_base::trunc 

==

std::ios_base::out | std::ios_base::trunc 

这实际上是你想要的:打开文件进行写入,如果存在则截断它。

(当然std::ios_base::trunc是多余的,因为通过0x499602d2提到的 - 你可以指定只std::ios_base::out

+0

为什么它等于std :: ios_base :: trunc? – nbro 2014-09-04 16:55:54

+0

@usar'out | sapp&out | trunc' =='out | (sapp&out)| trunc' =='out | 0 | trunc' =='out | trunc' – 2014-09-04 17:12:43

+0

它也可以工作,如果我使用:'_fs.open(_path,(std :: ios_base :: out | std :: ios_base :: trunc)&(std :: ios_base :: out | std :: ios_base :: app));' – nbro 2014-09-04 17:34:03

1

我想以追加模式打开文件,但是,如果文件已经存在,请覆盖其内容。

这与简单地清空文件无论它是否存在相同。 std::ofstream()创建一个新的空文件,如果其中一个不存在,则默认情况下其内容将被删除,除非您使用std::ios_base::app

所以这听起来像你只想打开只有std::ios_base::out的文件。

+0

@usar当你用'out'打开一个输出文件时(这是默认的btw)擦除文件的内容。除非你使用'app'来追加。 – 0x499602D2 2014-09-04 16:42:29