tags:

views:

202

answers:

3

I have been having a problem identifying a flash drive in my code.

Luckily my code can be run from the flash drive. So is there a way in C (or C++) to tell what drive letter (or drive name) a program is running on?

Reason I need to know is when I plug the USB drive in, it is running a program that copies files from the computer to the USB drive itself.

+3  A: 

GetModuleFileName can find out the driver letter for you, like this:

TCHAR ExeName[MAX_PATH];
GetModuleFileName(NULL, ExeName, MAX_PATH);
TCHAR DriveLetter = ExeName[0];

You might find the GetDriveType API useful as well.

RichieHindle
A: 

Somewhere on your C/C++ program you should have a main

like int main(int argc, char** argv)

the first argument of argv hold the path of your application

Eric
the first argument actually holds the application name rather than a full path to it.
John T
+1  A: 

You could use the ISO C++ _getcwd function to get the current working directory of your application like so:

#include <direct.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    char buf[255];
    _getcwd(buf,255);
    printf("%c",buf[0]);
    return 0;
}

The char array buf will contain the path to your executable and buf[0] should supply you with just the letter of the drive.

John T
nitpick: _getcwd() is not ISO standard. getcwd() is part of POSIX; MS adds a '_' prefix because they don't consider POSIX standard enough to include in the CRT without the 'implementation-defined name' prefix.
Michael Burr
Also the current working directory will not necessarily be the directory where the application image lives (however depending on how the program should act, the current directory may be more appropriate to use than the application directory).
Michael Burr
It isn't standard it's conformant. I never used the word standard in my post.
John T
ISO is the International Organisation for Standards, so you did in fact refer to it, unintentionally perhaps. And the reason that Microsoft calls is "conformant" is because ISO C++ reserves _[a-z].* for implementation extensions. So _getcwd is a conformant extension of the standard, not part of ISO C++.
MSalters