Home > Backend Development > C++ > How to Get the Current Directory in C ?

How to Get the Current Directory in C ?

Linda Hamilton
Release: 2024-11-09 03:32:02
Original
281 people have browsed it

How to Get the Current Directory in C  ?

Retrieving the Current Directory

Getting the current directory is a frequent task in programming. For instance, suppose you want to create a file in the same directory where the executable is running. To do this, you need to obtain the current directory's path.

However, when using the GetCurrentDirectory() function as shown below:

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

you may encounter an exception. Instead of GetCurrentDirectory(), you should use GetModuleFileName() to retrieve the executable path.

TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName(NULL, buffer, MAX_PATH);
Copy after login

For obtaining the directory path without the file name, you can employ the following C function:

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

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

int main() {
    std::cout << "my directory is " << ExePath() << "\n";
}
Copy after login

The above is the detailed content of How to Get the Current Directory in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template