本文主要针对Linux系统和C++语言描述
绝对路径的用法
绿色双引号里面的就是路径,C++路径一般用std::string表示,绝对路径就是把目录的所有层级都写出来,比如,
std::string test_path = "/home/scarlett/test_ws/test_pkg/src/test.cpp";
但是这样,不利于程序迁移到另一个系统,举个例子
在Linux下,我的主目录为:/home/scarlett
,但是另一个用户的主目录是/home/edward
,那上一行代码在edward那儿运行是会报错的,因为在他那里这个目录是不存在,最直接的修改办法是将scarlett修改为edward,如下:
std::string test_path = "/home/edward/test_ws/test_pkg/src/test.cpp";
但是总不能每换一个用户就修改一遍吧?使用相对路径可以在很大程度上避免该问题。
相对路径的两种用法
第一种:拼接
看下面这个例程:
#include <iostream>
#include <cstdlib> // for getenv
#include <string>
int main() {
std::string homeDir;
const char *homeEnv = getenv("HOME"); // Get the value of the HOME environment variable
if (homeEnv) {
homeDir = homeEnv; // Convert the environment variable to a C++ string
}
else {
std::cerr << "Unable to get HOME environment variable" << std::endl;
return 1;
}
// Use the home directory in a path
std::string filePath = homeDir + "/myfile.txt";
std::cout << "File path: " << filePath << std::endl;
return 0;
}
getenv()
用于获取运行该C++代码的当前用户的主目录,HOME是环境变量,保存的是当前用户的主目录。将该环境变量转化为字符串,然后和相对目录拼接,即可得到完整的路径。如果环境变量没有设置,则会报错。
查看HOME
的内容:
echo $HOME # 我的输出是:/home/scarlett
查看所有环境变量
printenv
第二种:用 .
在下面的例程中,
myfile.txt
在当前目录下
parentfile.txt
在当前目录的上一级目录下
subfile.txt
在当前目录的子目录下
grandparentfile.txt
在上一级目录的上一级目录下
#include <iostream>
#include <fstream>
int main() {
std::string relativePath = "./myfile.txt"; // Relative path to a file in the same directory
std::ifstream inputFile(relativePath);
if (inputFile.is_open()) {
// Do something with the file
inputFile.close();
}
else {
std::cout << "Unable to open file: " << relativePath << std::endl;
}
return 0;
}
#include <iostream>
#include <fstream>
int main() {
// Relative path to a file in the parent directory
std::string parentPath = "../parentfile.txt";
std::ifstream parentFile(parentPath);
if (parentFile.is_open()) {
// Do something with the file
parentFile.close();
}
else {
std::cout << "Unable to open file: " << parentPath << std::endl;
}
// Relative path to a file in a subdirectory
std::string subdirPath = "./subdir/subfile.txt";
std::ifstream subFile(subdirPath);
if (subFile.is_open()) {
// Do something with the file
subFile.close();
}
else {
std::cout << "Unable to open file: " << subdirPath << std::endl;
}
// Relative path to a file in a grandparent directory
std::string grandparentPath = "../../grandparent/grandparentfile.txt";
std::ifstream grandparentFile(grandparentPath);
if (grandparentFile.is_open()) {
// Do something with the file
grandparentFile.close();
}
else {
std::cout << "Unable to open file: " << grandparentPath << std::endl;
}
return 0;
}