Home > Backend Development > C++ > body text

How to Retrieve the Current Directory Path in C ?

Patricia Arquette
Release: 2024-11-08 10:29:02
Original
644 people have browsed it

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);
Copy after login

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";
}
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!