Home  >  Article  >  Backend Development  >  How to Retrieve the Current Directory Path in C ?

How to Retrieve the Current Directory Path in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-08 10:29:02646browse

How to Retrieve the Current Directory Path in C  ?

Getting Current Directory in C

When creating a file in the current directory where the program is executing, it's crucial to obtain the correct path. However, in your code, you encounter an exception during GetCurrentDirectory().

Understanding the Exception

The exception is likely caused by an invalid argument passed to GetCurrentDirectory. You need to allocate a buffer to store the directory path before calling this function.

Alternative Solution Using GetModuleFileName

To retrieve the path of the executable file, consider using GetModuleFileName instead:

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

Extracting Directory Path

To get the directory path without the file name, you can use the following 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";
}

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

Statement:
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