C++ 如何获取当前目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/875249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:44:16  来源:igfitidea点击:

How to get Current Directory?

c++windows

提问by Ivan Prodanov

I've been doing this in C# and Delphi ,but C++ is evil.The purpose is to create a file in the current directory(where the executable is running).

我一直在 C# 和 Delphi 中这样做,但 C++ 是邪恶的。目的是在当前目录(可执行文件运行的地方)中创建一个文件。

My code:

我的代码:

LPTSTR NPath = NULL;
DWORD a = GetCurrentDirectory(MAX_PATH,NPath);
HANDLE hNewFile = CreateFile(NPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);

I get exception at GetCurrentDirectory().

我在 GetCurrentDirectory() 处遇到异常。

Please tell me why I get an exception and how do I make it easier in C++?

请告诉我为什么会出现异常以及如何在 C++ 中使其更容易?

回答by

I would recommend reading a book on C++ before you go any further, as it would be helpful to get a firmer footing. Accelerated C++by Koenig and Moo is excellent.

我建议你在继续之前阅读一本关于 C++ 的书,因为这将有助于获得更稳固的立足点。Koenig 和 Moo 的Accelerated C++非常出色。

To get the executable path use GetModuleFileName:

要获取可执行路径,请使用GetModuleFileName

char buffer[MAX_PATH];
GetModuleFileName( NULL, buffer, MAX_PATH );

Here's a C++ function that gets the directory without the file name:

这是一个 C++ 函数,它获取没有文件名的目录:

#include <windows.h>
#include <string>
#include <iostream>
using namespace std;;

string ExePath() {
    char buffer[MAX_PATH];
    GetModuleFileName( NULL, buffer, MAX_PATH );
    string::size_type pos = string( buffer ).find_last_of( "\/" );
    return string( buffer ).substr( 0, pos);
}

int main() {
    cout << "my directory is " << ExePath() << "\n";
}

回答by avakar

GetCurrentDirectorydoes not allocate space for the result, it's up to you to do that.

GetCurrentDirectory不会为结果分配空间,这取决于您。

TCHAR NPath[MAX_PATH];
GetCurrentDirectory(MAX_PATH, NPath);

Also, take a look at Boost.Filesystemlibrary if you want to do this the C++ way.

另外,如果您想以 C++ 方式执行此操作,请查看Boost.Filesystem库。

回答by Rasmus Dall

The question is not clear whether the current working directory is wanted or the path of the directory containing the executable.

问题不清楚是需要当前工作目录还是包含可执行文件的目录的路径。

Most answers seem to answer the latter.

大多数答案似乎都回答了后者。

But for the former, and for the second part of the question of creating the file, the C++17 standard now incorporates the filesystem library which simplifies this a lot:

但是对于前者,对于创建文件的第二部分问题,C++17 标准现在合并了文件系统库,这大大简化了这一点:

#include <filesystem>
#include <iostream>

std::filesystem::path cwd = std::filesystem::current_path() / "filename.txt";
std::ofstream file(cwd.string());
file.close();

This fetches the current working directory, adds the filename to the path and creates an empty file. Note that the path object takes care of os dependent path handling, so cwd.string() returns an os dependent path string. Neato.

这将获取当前工作目录,将文件名添加到路径并创建一个空文件。请注意,路径对象负责操作系统相关路径处理,因此 cwd.string() 返回一个操作系统相关路径字符串。尼托。

回答by cdiggins

IMHO here are some improvements to anon's answer.

恕我直言,这里是对匿名回答的一些改进。

#include <windows.h>
#include <string>
#include <iostream>

std::string GetExeFileName()
{
  char buffer[MAX_PATH];
  GetModuleFileName( NULL, buffer, MAX_PATH );
  return std::string(buffer);
}

std::string GetExePath() 
{
  std::string f = GetExeFileName();
  return f.substr(0, f.find_last_of( "\/" ));
}

回答by MsLate

#include <iostream>    
#include <stdio.h>
#include <dirent.h>

std::string current_working_directory()
{
    char* cwd = _getcwd( 0, 0 ) ; // **** microsoft specific ****
    std::string working_directory(cwd) ;
    std::free(cwd) ;
    return working_directory ;
}

int main(){
    std::cout << "i am now in " << current_working_directory() << endl;
}

I failed to use GetModuleFileName correctly. I found this work very well. just tested on Windows, not yet try on Linux :)

我未能正确使用 GetModuleFileName。我发现这项工作非常好。刚刚在 Windows 上测试过,还没有在 Linux 上尝试过:)

回答by Jj Rivero

Please don't forget to initialize your buffers to somethingbefore utilizing them. And just as important, give your string buffers space for the ending null

在使用缓冲区之前,请不要忘记将缓冲区初始化为某些内容。同样重要的是,为结尾的 null 提供字符串缓冲区空间

TCHAR path[MAX_PATH+1] = L"";
DWORD len = GetCurrentDirectory(MAX_PATH, path);

Reference

参考

回答by yves Baumes

You should provide a valid buffer placeholder. that is:

您应该提供一个有效的缓冲区占位符。那是:

TCHAR s[100];
DWORD a = GetCurrentDirectory(100, s);

回答by freezotic

#include <windows.h>
using namespace std;

// The directory path returned by native GetCurrentDirectory() no end backslash
string getCurrentDirectoryOnWindows()
{
    const unsigned long maxDir = 260;
    char currentDir[maxDir];
    GetCurrentDirectory(maxDir, currentDir);
    return string(currentDir);
}

回答by ProXicT

You can remove the filename from GetModuleFileName()with more elegant way:

您可以GetModuleFileName()使用更优雅的方式删除文件名:

TCHAR fullPath[MAX_PATH];
TCHAR driveLetter[3];
TCHAR directory[MAX_PATH];
TCHAR FinalPath[MAX_PATH];
GetModuleFileName(NULL, fullPath, MAX_PATH);
_splitpath(fullPath, driveLetter, directory, NULL, NULL);
sprintf(FinalPath, "%s%s",driveLetter, directory);

Hope it helps!

希望能帮助到你!

回答by ProXicT

An easy way to do this is:

一个简单的方法是:

int main(int argc, char * argv[]){
    std::cout << argv[0]; 
    std::cin.get();
}

argv[]is pretty much an array containing arguments you ran the .exe with, but the first one is always a path to the executable. If I build this the console shows: C:\Users\Ulisse\source\repos\altcmd\Debug\currentdir.exe

argv[]几乎是一个包含您运行 .exe 所用参数的数组,但第一个始终是可执行文件的路径。如果我构建它,控制台会显示: C:\Users\Ulisse\source\repos\altcmd\Debug\currentdir.exe