如何获取当前目录? [英] How to get Current Directory?

查看:152
本文介绍了如何获取当前目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

我的代码:

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

我在GetCurrentDirectory()获得异常。

I get exception at GetCurrentDirectory().

请告诉我为什么我得到一个异常,如何使它更容易在C + +?

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

推荐答案

在C ++上书之前,你要走得更远,因为这将有助于得到一个更坚实的基础。 Accelerated C ++ by Koenig and Moo is excellent。

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.

获取可执行路径使用 GetModuleFileName

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

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

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

#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";
}

这篇关于如何获取当前目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆