在目录中搜索文件

Search a file in a directory

本文关键字:搜索 文件      更新时间:2023-10-16

我在一个项目中工作,我需要知道一个文件在目录中是否唯一。那么,如何查找目录中是否存在文件呢?我有没有扩展名的文件名和目录路径。

我认为没有现成的函数,但你可以使用这样的东西:

static bool fileExists( const char *path )
{
    const DWORD attr = ::GetFileAttributesA( path );
    return attr != INVALID_FILE_ATTRIBUTES &&
           ( ( attr & FILE_ATTRIBUTE_ARCHIVE ) || ( attr & FILE_ATTRIBUTE_NORMAL ) );
}

这将验证它是一个"正常"文件。如果您也想处理隐藏文件,则可能需要添加/删除标志检查。

我更喜欢用c++的方式来做这件事,但是你提到了一个visual c++标签,所以有一种方法可以在visual c++上做到这一点。净:

using <mscorlib.dll>
using namespace System;
using namespace System::IO;
bool search(String folderPath, String fileName) {
    String* files[] = Directory::GetFiles(folderPath, fileName+".*"); //search the file with the name fileName with any extension (remember, * is a wildcard)
    if(files->getLength() > 0)
        return true; //there are one or more files with this name in this folder
    else
        return false; //there arent any file with this name in this folder
}