我如何打开一个文件进行阅读&写,创建它,如果它不存在,不截断它? [英] How can I open a file for reading & writing, creating it if it does not exist, without truncating it?
问题描述
std :: fstream
的I / O标志的正确设置是什么,其中我想要从和
What is the proper set of I/O flags for a std::fstream
, where I want to be able to read from and write to the file, without truncating the file if it exists, but creating it if it does not?
我试过了
std::ios::binary | std::ios::in | std::ios::out
std::ios::binary | std::ios::in | std::ios::out | std::ios::ate
但是如果文件不存在,
but neither of these create the file if it does not already exist.
我不想要 std :: ios :: app
,因为我也需要能够随意放置文件,同时放置 和放置游标。
I don't want std::ios::app
, because I also need to be able to seek around the file at will, with both the get and put cursors.
一个解决方法,首先要实例化一个 std :: ofstream
,然后立即关闭它,并打开我真正想要的流,但是这似乎很乱,如果它可以避免与单个流对象。
One workaround, I suppose, would be to instantiate an std::ofstream
first, then immediately close it and open the stream I really want, but that seems messy if it can be avoided with a single stream object.
推荐答案
现在,我的结论是 std :: ios :: in $
At this time, I'm concluding that std::ios::in
outright prevents this, and that I must use the workaround.
因此:
if (!std::ostream(path.c_str()))
throw std::runtime_error("Could not create/open file");
std::fstream fs(path.c_str(), std::ios::binary | std::ios::in | std::ios::out);
if (!fs)
throw std::runtime_error("Could not open file");
// ... use `fs`
这篇关于我如何打开一个文件进行阅读&写,创建它,如果它不存在,不截断它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!