1. \\雙反斜杠,傳統寫法,需轉義
-
在 C/C++ 字符串中,
\
?具有特殊含義,例如:-
\n
?表示換行 -
\t
?表示制表符 -
\"
?表示雙引號
-
-
如果要表示一個真正的反斜杠,必須寫成?
\\
,否則編譯器會將其解釋為轉義字符。
2. /正斜杠,跨平臺兼容
Qt 和現代 Windows API 都支持正斜杠/作為路徑分隔符
3. 使用原始字符串(C++11 及以上)
R"(C:\Users\file.txt)"
C++11 特性,避免轉義
4. 雙正斜杠(//
)?
在文件路徑中通常沒有特殊含義,它會被當作兩個單獨的正斜杠處理。
文件系統(包括 Windows 和 Unix-like 系統)會自動將多個連續的斜杠合并為單個?/
有中文加u8
如何顯示當前路徑
win
#include <direct.h>
#include <iostream>int main() {char cwd[FILENAME_MAX];_getcwd(cwd, sizeof(cwd));std::cout << "Current working directory: " << cwd << std::endl;return 0;
}
linux
#include <iostream>
#include <unistd.h>int main() {char cwd[PATH_MAX];if (getcwd(cwd, sizeof(cwd)) != NULL) {std::cout << "Current working directory: " << cwd << std::endl;} else {std::cerr << "getcwd() error" << std::endl;}return 0;
}
跨平臺(c++17)
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;int main() {fs::path currentPath = fs::current_path();std::cout << "Current working directory: " << currentPath << std::endl;return 0;
}