c++获取指定目录下的文件名

2025-02-27 15:23:54
推荐回答(3个)
回答1:

可以使用searchenv函数来实现,参考代码如下:

int main( void )
{
   char pathbuffer[_MAX_PATH];
   char searchfile[] = "×.EXE";
   char envvar[] = "PATH";
 
   // Search for file in PATH environment variable:
   _searchenv( searchfile, envvar, pathbuffer ); // C4996
   // Note: _searchenv is deprecated; consider using _searchenv_s
   if( *pathbuffer != '\0' )
      printf( "Path for %s:\n%s\n", searchfile, pathbuffer );
   else
      printf( "%s not found\n", searchfile );
}

回答2:

3.34 icePub_getPathList

l 函数原型:
int WINAPI icePub_getPathList(char *strCurrentPath,char *strPathList,int maxLen,int flag)
输入:strCurrentPath 待搜索路径名
maxLen strPathList最大长度
flag 信息标志,0 只文件名,1 文件长度
输出:strPathList 带全路径文件名

VC sample代码:
char buffer[1024*10+1];
{
typedef int (WINAPI ICEPUB_GETPATHLIST)( char *strCurrentPath,char *strPathList,int maxLen,int flag);
ICEPUB_GETPATHLIST *icePub_getPathList = 0;
HINSTANCE hDLLDrv = LoadLibrary("icePubDll.dll");
if(hDLLDrv)
{
icePub_getPathList = (ICEPUB_GETPATHLIST *)GetProcAddress(hDLLDrv, "icePub_getPathList");
}

if(icePub_getPathList != NULL)
{
int a;
buffer[0]=0;
a=icePub_getPathList("C:\\",buffer,1024*10,1);
AfxMessageBox(buffer);
}
if(hDLLDrv)
FreeLibrary(hDLLDrv);
}

http://dl.icese.net/dev.php?f=icePubDll.rar 下载

回答3:


#define _WIN32_WINNT 0x0400

#include
#include

int main()
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;

int find = 1;
hFind = FindFirstFile("*.jpg", &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf ("Invalid File Handle. GetLastError reports %d\n", GetLastError ());
return (0);
}
else
{
while(find)
{
printf ("The first file found is %s\n", FindFileData.cFileName);
find = FindNextFile(hFind, &FindFileData);
}
FindClose(hFind);
return (1);
}
}