디렉토리가 있는지 확인하는 휴대용 방법 [Windows/Linux, C]
지정된 디렉토리가 있는지 확인하고 싶습니다.Windows에서 이 작업을 수행하는 방법을 알고 있습니다.
BOOL DirectoryExists(LPCTSTR szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
및 Linux:
DIR* dir = opendir("mydir");
if (dir)
{
/* Directory exists. */
closedir(dir);
}
else if (ENOENT == errno)
{
/* Directory does not exist. */
}
else
{
/* opendir() failed for some other reason. */
}
하지만 나는 이것을 하는 휴대용 방법이 필요하다.어떤 OS를 사용하든 디렉토리가 존재하는지 확인할 수 있는 방법이 있습니까?C 스탠다드 도서관 방식?
프리프로세서의 디렉티브를 사용하고, 그 함수를 다른 OS로 호출할 수 있는 것은 알고 있습니다만, 이것은 Im이 요구하는 솔루션이 아닙니다.
적어도 지금으로선 이렇게 끝나게다만,
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
int dirExists(const char *path)
{
struct stat info;
if(stat( path, &info ) != 0)
return 0;
else if(info.st_mode & S_IFDIR)
return 1;
else
return 0;
}
int main(int argc, char **argv)
{
const char *path = "./TEST/";
printf("%d\n", dirExists(path));
return 0;
}
stat()는 Linux, UNIX 및 Windows에서도 작동합니다.
#include <sys/types.h>
#include <sys/stat.h>
struct stat info;
if( stat( pathname, &info ) != 0 )
printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR ) // S_ISDIR() doesn't exist on my windows
printf( "%s is a directory\n", pathname );
else
printf( "%s is no directory\n", pathname );
C++17에서는std::filesystem::is_directory
(https://en.cppreference.com/w/cpp/filesystem/is_directory) 를 참조해 주세요.를 받아들입니다.std::filesystem::path
유니코드 경로로 구성할 수 있는 객체입니다.
상기의 승인된 답변이 명확하지 않은 것을 발견했기 때문에, OP는 잘못된 솔루션을 제공하고 있습니다.따라서 나는 아래의 사례가 다른 사람들에게 도움이 되기를 바란다.해결책은 좀 더 또는 덜 뿐만 아니라 휴대용이다.
/******************************************************************************
* Checks to see if a directory exists. Note: This method only checks the
* existence of the full path AND if path leaf is a dir.
*
* @return >0 if dir exists AND is a dir,
* 0 if dir does not exist OR exists but not a dir,
* <0 if an error occurred (errno is also set)
*****************************************************************************/
int dirExists(const char* const path)
{
struct stat info;
int statRC = stat( path, &info );
if( statRC != 0 )
{
if (errno == ENOENT) { return 0; } // something along the path does not exist
if (errno == ENOTDIR) { return 0; } // something in path prefix is not a dir
return -1;
}
return ( info.st_mode & S_IFDIR ) ? 1 : 0;
}
사용 증대 효과::파일 시스템, 그것은 당신과 너 모든 못생긴 세부 사항 추상화 같은 종류의 휴대용을.
당신은 OS의 물질로부터 추상화 하기는 GTK 허물없는 사용할 수 있다.
말만 앞세우는 문제를 해결해 준 g_dir_open()는 기능을 제공한다.
위의 예를 Windows와 Linux를 위해 사용할 수 있[_access]1을 사용하지 않습니다.코드 샘플(Windows)[통계량]2, _access()과 최신 파일 시스템의[존재하]3을 시험하다.
#include <iostream>
#include <Windows.h>
#include <io.h>
#include <filesystem>
#include <vector>
#include <string>
using namespace std;
namespace fs = std::filesystem;
std::vector<std::string> DirPaths
{
"G:\\My-Shcool-2021-22",
"\\\\192.168.111.8\\Oaco\\RotData\\VV-VA",
"\\\\192.168.111.15\\5500\\C-drive\\Oaco\\RotateEarthProject", "\\\\192.168.111.18\\d$\\Mercurial\\Workspace\\HideMoon\\Win32\\Debug",
"Z:\\SuperSaver" //mapped network drive; symbolic link
};
/* test if the path is a directory
*/
void TestDirExists ()
{
int erno =-1;
struct stat info {};
auto ErrorMsg = [&](std::string path)
{
_get_errno(&erno);
if (erno == EACCES)
cout << "access denied " << path << endl;
else if (erno == ENOENT)
cout << "dir path not found " << path << endl;
else if (erno == EINVAL)
cout << "invalid parameter " << path << endl;
};
for (const auto &dp : DirPaths)
{
erno = -1;
if (stat(dp.c_str(), &info) != 0)
ErrorMsg(dp);
if (_access(dp.c_str(), 0) != 0)
ErrorMsg(dp);
if (fs::exists(dp)==0)
ErrorMsg(dp);
if(erno < 0)
cout << "#Dir Found: " << dp << endl;
}
}[1]:https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/access-waccess?view=msvc-170[2]:https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/stat-functions?view=msvc-170[3]:https://en.cppreference.com/w/cpp/filesystem/exists.
언급URL:https://stackoverflow.com/questions/18100097/portable-way-to-check-if-directory-exists-windows-linux-c
'programing' 카테고리의 다른 글
printf()를 사용하여 출력할 문자열의 글자 수를 지정하는 방법이 있습니까? (0) | 2022.07.29 |
---|---|
형식 설명 2.6.1에서 vue js @Component를 사용하는 방법은 무엇입니까? (0) | 2022.07.29 |
c에서 벡터를 복제하는 방법? (0) | 2022.07.29 |
왜 소수의 비디오 게임만 자바어로 쓰여져 있는 거죠? (0) | 2022.07.28 |
Vue 3 Modal이 다시 열 때 이전 데이터를 가지고 돌아오다 (0) | 2022.07.28 |