C++ 在目录中搜索文件

C++ 在目录中搜索文件,c++,visual-c++,C++,Visual C++,我在一个项目中工作,我需要知道一个文件在一个目录中是否是唯一的。 那么我如何才能找到一个文件是否存在于一个目录中呢? 我有一个没有扩展名的文件名和目录路径。我想没有现成的函数,但您可以使用如下内容: static bool fileExists( const char *path ) { const DWORD attr = ::GetFileAttributesA( path ); return attr != INVALID_FILE_ATTRIBUTES &&

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

我想没有现成的函数,但您可以使用如下内容:

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

这将验证它是否为“正常”文件。如果您还想处理隐藏文件,您可能需要添加/删除标志检查。

我认为没有现成的功能,但您可以使用以下类似的功能:

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

这将验证它是否为“正常”文件。如果您想处理隐藏文件,您可能需要添加/删除标志检查。

< P>我更喜欢用C++方式来做这件事,但您提到了Visual C++标签,因此在VisualC++.NET: < /P>有一种方法可以做到这一点。
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

}
使用
使用名称空间系统;
使用名称空间系统::IO;
布尔搜索(字符串文件夹路径、字符串文件名){
String*files[]=Directory::GetFiles(folderPath,fileName+“*”);//搜索名为fileName且具有任何扩展名的文件(请记住,*是通配符)
如果(文件->getLength()>0)
return true;//此文件夹中有一个或多个同名文件
其他的
return false;//此文件夹中没有具有此名称的文件
}

我喜欢用C++方式来做这个,但是你提到了Visual C++标签,所以有一种方法可以在VisualC++.NET上完成:

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

}
使用
使用名称空间系统;
使用名称空间系统::IO;
布尔搜索(字符串文件夹路径、字符串文件名){
String*files[]=Directory::GetFiles(folderPath,fileName+“*”);//搜索名为fileName且具有任何扩展名的文件(请记住,*是通配符)
如果(文件->getLength()>0)
return true;//此文件夹中有一个或多个同名文件
其他的
return false;//此文件夹中没有具有此名称的文件
}

你所说的“独一无二”是什么意思?为什么没有扩展?你的意思是想知道是否有文件的扩展名不同?你说的“唯一”是什么意思?为什么没有扩展?你的意思是想知道是否有文件的扩展名不同?谢谢,这正是我需要的,但我只需要知道一件事,参数(path=directory+filename+extension)?@nidahl:Right;
path
参数是文件系统中的实际路径。谢谢,这正是我需要的,但我只需要知道一件事参数(path=目录+文件名+扩展名)?@nidahl:对;
path
参数是文件系统中的实际路径。