C++获取文件所在的目录
时间: 2023-09-03 16:15:56 浏览: 53
可以使用以下代码获取文件所在的目录:
```cpp
#include <iostream>
#include <string>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
int main() {
string filePath = "C:/Users/username/Documents/example.txt";
fs::path pathObj(filePath);
string directory = pathObj.parent_path().string();
cout << directory << endl;
return 0;
}
```
这里使用了 C++17 中的 `std::filesystem` 库,需要添加 `-lstdc++fs` 编译选项。
相关问题
devc++读取文件时文件应放在哪
文件应该放在当前运行的程序所在的工作目录中。在 Dev-C++ 中,可以通过在菜单栏中选择“Project” -> “Open Project Options” -> “Directories” -> “Executable files” 来找到当前程序的工作目录。在该目录下创建一个文件夹,把需要读取的文件放在其中,然后在程序中使用相对路径来读取该文件。例如,如果文件夹名为"data",文件名为"test.txt",则可以使用以下代码读取:
```
ifstream infile("data/test.txt");
```
注意,如果文件不存在,程序会报错。因此,在读取文件之前,最好先检查文件是否存在。
c++,获取当前进程所在目录
在 C++ 中,可以使用以下代码获取当前进程所在目录:
```c++
#include <iostream>
#include <windows.h>
int main() {
char buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);
std::string::size_type pos = std::string(buffer).find_last_of("\\/");
std::cout << std::string(buffer).substr(0, pos) << std::endl;
return 0;
}
```
其中,`GetModuleFileName` 函数可以获取当前进程的可执行文件路径,`std::string::find_last_of` 函数可以查找字符串中最后一个出现指定字符的位置,`std::string::substr` 函数可以获取字符串的子串。最终输出的是该路径的目录部分。需要注意的是,这里使用了 Windows 平台下的 API 函数,如果在 Linux 平台下需要使用其他方式实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)