development

파일 이름에서 디렉토리 이름 얻기

big-blog 2020. 10. 15. 08:01
반응형

파일 이름에서 디렉토리 이름 얻기


파일 이름 (C : \ folder \ foo.txt)이 있고 관리되지 않는 C ++에서 폴더 이름 (C : \ folder)을 검색해야합니다. C #에서는 다음과 같이합니다.

string folder = new FileInfo("C:\folder\foo.txt").DirectoryName;

관리되지 않는 C ++에서 파일 이름에서 경로를 추출하는 데 사용할 수있는 함수가 있습니까?


이를위한 표준 Windows 함수 인 PathRemoveFileSpec이 있습니다. Windows 8 이상 만 지원하는 경우 대신 PathCchRemoveFileSpec 을 사용하는 것이 좋습니다 . 다른 개선 사항 중에서 더 이상 MAX_PATH(260) 문자로 제한되지 않습니다 .


Boost.Filesystem 사용 :

boost::filesystem::path p("C:\\folder\\foo.txt");
boost::filesystem::path dir = p.parent_path();

http://www.cplusplus.com/reference/string/string/find_last_of/의

// string::find_last_of
#include <iostream>
#include <string>
using namespace std;

void SplitFilename (const string& str)
{
  size_t found;
  cout << "Splitting: " << str << endl;
  found=str.find_last_of("/\\");
  cout << " folder: " << str.substr(0,found) << endl;
  cout << " file: " << str.substr(found+1) << endl;
}

int main ()
{
  string str1 ("/usr/bin/man");
  string str2 ("c:\\windows\\winhelp.exe");

  SplitFilename (str1);
  SplitFilename (str2);

  return 0;
}

C ++ 17에는 std::filesystem::path메소드를 사용 하는 클래스가 있습니다 parent_path.

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
    for(fs::path p : {"/var/tmp/example.txt", "/", "/var/tmp/."})
        std::cout << "The parent path of " << p
                  << " is " << p.parent_path() << '\n';
}

가능한 출력 :

The parent path of "/var/tmp/example.txt" is "/var/tmp"
The parent path of "/" is ""
The parent path of "/var/tmp/." is "/var/tmp"

왜 그렇게 복잡해야합니까?

#include <windows.h>

int main(int argc, char** argv)         // argv[0] = C:\dev\test.exe
{
    char *p = strrchr(argv[0], '\\');
    if(p) p[0] = 0;

    printf(argv[0]);                    // argv[0] = C:\dev
}

Use boost::filesystem. It will be incorporated into the next standard anyway so you may as well get used to it.


 auto p = boost::filesystem::path("test/folder/file.txt");
 std::cout << p.parent_path() << '\n';             // test/folder
 std::cout << p.parent_path().filename() << '\n';  // folder
 std::cout << p.filename() << '\n';                // file.txt

You may need p.parent_path().filename() to get name of parent folder.


_splitpath is a nice CRT solution.


I'm so surprised no one has mentioned the standard way in Posix

Please use basename / dirname constructs.

man basename


Standard C++ won't do much for you in this regard, since path names are platform-specific. You can manually parse the string (as in glowcoder's answer), use operating system facilities (e.g. http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx ), or probably the best approach, you can use a third-party filesystem library like boost::filesystem.


Just use this: ExtractFilePath(your_path_file_name)

참고URL : https://stackoverflow.com/questions/3071665/getting-a-directory-name-from-a-filename

반응형