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
cpp
#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
cpp
#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)
cpp
#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;
}