我想用标准库打开一个文件进行写入,但如果文件已经存在,打开文件应该会失败。
从我在文档中可以读到的内容来看,ofstream::open 只允许追加或截断。
我当然可以尝试打开以读取以检查文件是否存在,如果不存在则重新打开以进行写入,但不能保证文件不会被其他进程在其间创建。
有人可以确认这在标准库(std::iostream)或 C 函数(FILE* 函数)的 C++ 中是不可能的吗
最佳答案
自 C11(因此也在 C++17 中),对于 fopen
,您可以使用模式 "x"
— 独占模式,参见 this :
File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This flag forces the function to fail if the file exists, instead of overwriting it.
关于C++ 打开文件只在不存在时写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37709395/