prgchDirPath是一个目录路径。 文件不存在。 但我想确定目录/路径是否存在。 以下API可以帮助我吗?如果有,怎么样?
unsigned char IsFilePathCorrect(char* prgchDirPath)
{
WIN32_FIND_DATA FindFileData;
HANDLE handle;
int found=0;
//1. prgchDirPath is char pointer. But expected is LPCWSTR.
//How to change this?
//2. prgchDirPath is a directory path. File is not existed.
//But I want to make sure if directory/path exists or not.
//Can the API below helps me? if yes, how?
handle = FindFirstFile(prgchDirPath, &FindFileData);
if(handle != INVALID_HANDLE_VALUE)
found = 1;
if(found)
{
FindClose(handle);
}
return found;
}
我想检查目录路径是否存在。请提供一个示例代码。谢谢。
答案 0 :(得分:2)
您可以简单地使用access
,它在Windows,Linux,Mac等广泛支持:access(filepath, 0)
如果文件存在则返回0
,否则返回错误代码。在Windows上,您需要#include <io.h>
。
答案 1 :(得分:0)
如何使用getAttributes函数执行此操作: -
BOOL DirectoryExists(LPCTSTR szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
或者您也可以尝试: -
#include <io.h> // For access().
#include <sys/types.h> // For stat().
#include <sys/stat.h> // For stat().
bool DirectoryExists( const char* path){
if( _access( path, 0 ) == 0 ){
struct stat s;
stat( path, &s);
return (s.st_mode & S_IFDIR) != 0;
}
return false;
}
答案 2 :(得分:0)
如果不使用任何Windows API,您可以检查路径是否正确,如下所示
/*
* Assuming that prgchDirPath is path to a directory
* and not to any file.
*/
unsigned char IsFilePathCorrect(char* prgchDirPath)
{
FILE *fp;
char path[MAX_PATH] = {0};
strcpy(path, prgchDirPath);
strcat(path, "/test.txt");
fp = fopen(path, "w");
if (fp == NULL)
return 0;
fclose(fp);
return 1;
}
答案 3 :(得分:0)
#include<stdio.h>
#include<fcntl.h>
#define DEVICE "test.txt"
int main()
{
int value = 0;
if(access(DEVICE, F_OK) == -1) {
printf("file %s not present\n",DEVICE);
return 0;
}
else
printf("file %s present, will be used\n",DEVICE);
return 0;
}