21xrx.com
2024-09-20 00:48:27 Friday
登录
文章检索 我的文章 写文章
C++如何获取当前目录?
2023-07-03 02:38:36 深夜i     --     --
C++ 获取当前目录

在C++中,可能需要获取当前目录信息来实现一些操作,例如文件读取和写入。但是,如何在程序中获取当前目录信息呢?下面将介绍两种实现方法。

方法1:使用 头文件中提供的getcwd()函数

getcwd()函数用于获取当前工作目录的路径名。它的定义如下:


char *getcwd(char *buf, size_t size);

其中,buf为一个字符型指针,指向存储当前目录路径名的缓冲区。size为buf指向的缓冲区的大小。该函数返回指向当前工作目录路径名的指针,如果出现错误则返回NULL。

下面是一个示例使用getcwd()函数获取当前目录路径名的代码:


#include <iostream>

#include <unistd.h>

using namespace std;

int main()

{

  char cwd[1024];

  if (getcwd(cwd, sizeof(cwd)) != NULL)

    cout << "Current working directory is: " << cwd << endl;

   else {

    perror("getcwd() error");

    return 1;

  }

  return 0;

}

该程序中,使用getcwd()函数获取当前目录路径名,并打印输出结果。

方法2:使用 头文件中提供的current_path()函数

C++17引入了 头文件,该头文件提供了一系列可用于文件和目录操作的函数。其中,current_path()函数用于获取当前目录的路径名。它的定义如下:


std::filesystem::path current_path();

该函数返回一个std::filesystem::path类型的对象,即当前目录的路径名。下面是一个示例使用current_path()函数获取当前目录路径名的代码:


#include <iostream>

#include <filesystem>

using namespace std;

int main()

{

  filesystem::path path = filesystem::current_path();

  cout << "Current working directory is: " << path.string() << endl;

  return 0;

}

该程序中,使用current_path()函数获取当前目录路径名,并打印输出结果。

通过上述两种方法,我们可以在C++程序中获取当前目录路径名,以实现相应操作。选择哪种方法主要取决于C++的版本和具体需求。

  
  
下一篇: C++清空vector

评论区

{{item['qq_nickname']}}
()
回复
回复