1
  1. prgchDirPath 是字符指针。但预期的是 LPCWSTR。如何改变这个?
  2. 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;
    }
    

我想检查目录路径是否存在。请提供一个示例代码。谢谢你。

4

4 回答 4

2

您可以简单地使用access,它在 Windows、Linux、Mac 等上得到广泛支持:如果文件存在则access(filepath, 0)返回0,否则返回错误代码。在 Windows 上,您将需要#include <io.h>.

于 2013-09-15T07:03:31.273 回答
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;
}
于 2013-09-15T06:42:30.370 回答
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;
}
于 2013-09-16T07:36:31.850 回答
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;
    }
于 2013-09-15T06:49:48.077 回答