`fstream file; file.open(filename, ...)` 如何設置模式使文件不存在時不創建,僅檢查存在性?
#include <filesystem>
bool exists = std::filesystem::exists(filename);
#include <fstream>
bool exists = std::ifstream(filename).good(); // 僅讀打開,不創建
// 或
struct stat buffer;
bool exists = (stat(filename.c_str(), &buffer) == 0); // POSIX/Windows 通用
原最佳回答給出 `File.Exists(path)`,這是 **C#/.NET** 的 API,非 C++。請注意語言標籤區分。
| 模式組合 | 行為 |
|---|---|
| `std::ios::in` | 讀取,文件不存在失敗 (不創建) |
| `std::ios::out` | 寫入,文件不存在**創建**,存在則截斷 |
| `std::ios::app` | 追加,文件不存在**創建** |
| `std::ios::in \| std::ios::out` | 讀寫,文件不存在失敗 (不創建) |
若需「打開讀寫、不存在則創建」用 `std::ios::in | std::ios::out | std::ios::trunc` (會創建/截斷) 或分兩步:先 `exists` 判斷,再決定模式。