get directory from file path c++

前端 未结 11 1410
梦如初夏
梦如初夏 2020-12-13 14:45

What is the simplest way to get the directory that a file is in? I\'m using this to find the working directory.

string filename = \"C:\\MyDirectory\\MyFile.b         


        
11条回答
  •  北海茫月
    2020-12-13 15:12

    The quick and dirty:

    Note that you must also look for / because it is allowed alternative path separator on Windows

    #include 
    #include 
    
    std::string dirnameOf(const std::string& fname)
    {
         size_t pos = fname.find_last_of("\\/");
         return (std::string::npos == pos)
             ? ""
             : fname.substr(0, pos);
    }
    
    int main(int argc, const char *argv[])
    {
         const std::string fname = "C:\\MyDirectory\\MyFile.bat";
    
         std::cout << dirnameOf(fname) << std::endl;
    }
    

提交回复
热议问题