Getting user temporary folder path in Windows

后端 未结 9 1604
醉梦人生
醉梦人生 2020-12-30 00:45

How I can get the user\'s temp folder path in C++? My program has to run on Windows Vista and XP and they have different temp paths. How I can get it without losing compatib

9条回答
  •  离开以前
    2020-12-30 01:26

    As VictorV pointed out, GetTempPath returns a collapsed path. You'll need to use both the GetTempPath and GetLongPathName macros to get the fully expanded path.

    std::vector collapsed_path;
    TCHAR copied = MAX_PATH;
    while ( true )
    {
        collapsed_path.resize( copied );
        copied = GetTempPath( collapsed_path.size( ), collapsed_path.data( ) );
        if ( copied == 0 ) 
            throw std::exception( "An error occurred while creating temporary path" );
        else if ( copied < collapsed_path.size( ) ) break;
    }
    
    std::vector full_path;
    copied = MAX_PATH;
    while ( true )
    {
        full_path.resize( copied );
        copied = GetLongPathName( collapsed_path.data( ), full_path.data( ), full_path.size( ) );
        if ( copied == 0 ) 
            throw std::exception( "An error occurred while creating temporary path" );
        else if ( copied < full_path.size( ) ) break;
    }
    std::string path( std::begin( full_path ), std::end( full_path ) );
    

提交回复
热议问题