How to find out if this or that volume exists? For example, I need to do this:

  • if disk D exists, then create files there;
  • if not, create files on the C drive.

    3 answers 3

    The easiest way is to simply try to create the desired file (after checking its existence - in order not to overwrite it by accident ...)

    Otherwise, you must use the tools of a specific operating system, because in C ++ itself there is simply no such thing as a volume. As there is no it in a number of operating systems :)

    Here's how to do this in Windows:

    #include <stdio.h> #include <direct.h> #include <stdlib.h> #include <ctype.h> int main( void ) { int drive, curdrive; static char path[_MAX_PATH]; // Save current drive. curdrive = _getdrive(); printf( "Available drives are:\n" ); // If we can switch to the drive, it exists. for( drive = 1; drive <= 26; drive++ ) { if( !_chdrive( drive ) ) { printf( "%c:", drive + 'A' - 1 ); if( _getdcwd( drive, path, _MAX_PATH ) != NULL ) printf( " (Current directory is %s)", path ); putchar( '\n' ); } } // Restore original drive. _chdrive( curdrive ); } 
    • Well, yes) Are there any other ways? - Vlad
    • See amended answer. - Harry

    With support for c ++ 17 (or even c ++ 14 with the experimental part), you can use the following code to check for a particular disk based on the filesystem library:

     #include <iostream> #include <string> #include <filesystem> namespace fs = std::experimental::filesystem; int main() { for( char drive = 'a'; drive <= 'z'; ++drive ) { fs::path p = std::string(1, drive) + ":"; std::cout << std::boolalpha << p << " - " << fs::exists(p) << "\n"; } } 

      There is a very humane way:

       int n; char dd[4]; DWORD dr = GetLogicalDrives(); for( int i = 0; i < 26; i++ ) { n = ((dr>>i)&0x00000001); if( n == 1 ){ dd[0] = char(65+i); dd[1] = ':'; dd[2] = '\\'; dd[3] = 0; cout << "Available disk drives : " << dd << endl; } }