FILE *fp = fopen("D:\shapes.txt", "r"); // \s 被解析為轉義序列 (空格)
C/C++ 字符串字面量中 \ 為轉義字符前綴:
\s → 無定義行為(通常視為 s)。\n → 換行、\t → 制表符、\\ → 反斜杠。實際路徑變為 D:shapes.txt(無冒號反斜杠),系統找不到。
| 寫法 | 代碼 | 推薦場景 |
|---|---|---|
| 雙反斜杠 | "D:\\shapes.txt" | Windows 專用、直觀 |
| 正斜杠 | "D:/shapes.txt" | **跨平台首選**、C++17 std::filesystem 完美支持 |
| 原始字符串 (C++11) | R"(D:\shapes.txt)" | 包含大量反斜杠/引號的複雜路徑 |
#include
namespace fs = std::filesystem;
fs::path filePath = "D:/shapes.txt"; // 或 fs::path("D:") / "shapes.txt"
if (fs::exists(filePath)) {
std::ifstream ifs(filePath); // 自動處理路徑分隔符
// ...
}
"C:\new\file.txt" // \n → 換行,\f → 換頁
"C:\\new\\file.txt" // 正確
R"(C:\new\file.txt)" // 正確
**Windows 路徑在 C++ 中永遠用正斜杠
/** 或原始字符串。std::filesystem::path內部自動轉換為原生分隔符,代碼跨平台零修改。