gpt4 book ai didi

c - 打印给定路径中的所有文件和子目录

转载 作者:太空宇宙 更新时间:2023-11-04 08:34:31 25 4
gpt4 key购买 nike

因此,我正在编写一个程序来递归打印给定路径中的目录/子目录和文件。我能够进入第一个子目录并打印其中的所有文件。我现在的问题是我需要找到一种方法来后退一个目录级别并从我停止阅读的地方继续。直到条件在原始目录级别发生。

#include "Everything.h"
#include "Strsafe.h"

WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
LARGE_INTEGER fileSize;
DWORD dwError;

void showdir(TCHAR *szDir);

int _tmain(int argc, LPCTSTR argv[])
{


TCHAR szDir[MAX_PATH];
size_t lengthOfArg;

// verify number of parameters
if (argc != 2)
{
ReportError(_T("Error: Incorrect number of arguments"), 1, FALSE);
}

// get the length of the entered directory
StringCchLength(argv[1], MAX_PATH, &lengthOfArg);

// verify that the directory path is not too long
if (lengthOfArg > MAX_PATH - 2)
{
ReportError(_T("Error: Directory too long"), 2, FALSE);
}

// attach an asterisk (wildcard search char) to end of directory path
StringCchCopy(szDir, MAX_PATH, argv[1]);
StringCchCat(szDir, MAX_PATH, _T("*"));

showdir(szDir);
}

void showdir(TCHAR *szDir)
{
// begin the search; find the first file in the directory
hFind = FindFirstFile(szDir, &ffd);
if (hFind == INVALID_HANDLE_VALUE)
{
ReportError(_T("Error in searching"), 3, TRUE);
}

//hFind = FindFirstFile(szDir, &ffd);
while (FindNextFile(hFind, &ffd) != 0)
{
if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
{
fileSize.LowPart = ffd.nFileSizeLow;
fileSize.HighPart = ffd.nFileSizeHigh;
_tprintf(_T("%s %ld\n"), ffd.cFileName, fileSize.QuadPart);

}

// did we find a directory?
// ffd.dwFileAttributes says this is a directory (FILE_ATTRIBUTE_DIRECTORY)

if ((ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
&& (_tcscmp(ffd.cFileName, _T(".")) != 0 && (_tcscmp(ffd.cFileName, _T("..")) != 0)))
{
TCHAR fullpath[MAX_PATH];

StringCchCopy(fullpath, strlen(szDir) - 0, szDir);
StringCchCat(fullpath, MAX_PATH, ffd.cFileName);
StringCchCat(fullpath, MAX_PATH, "\\");
_tprintf(_T("<DIR> %s \n"), fullpath);
StringCchCat(fullpath, MAX_PATH, _T("*"));



showdir(fullpath);

}
// continue the search; try to find more files
}

// figure out if we encountered an error other than "no more files"
dwError = GetLastError();

if (dwError != ERROR_NO_MORE_FILES)
{
ReportError(_T("Error in searching"), 4, TRUE);
}

FindClose(hFind);

}

最佳答案

你的全局变量

WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
LARGE_INTEGER fileSize;
DWORD dwError;

都应该是 showdir()局部变量。然后每个递归级别都有自己的搜索句柄,当嵌套的 showdir()返回时,调用 showdir() 可以简单地继续枚举其目录。

另请注意,您的代码忽略了每个目录中的第一个文件(结果FindFirstFile())。您可以将其重写为(为简洁起见省略了错误检查):

hFind = FindFirstFile(szDir, &ffd);
do {

// ... handle ffd ...

} while (FindNextFile(hFind, &ffd))

关于c - 打印给定路径中的所有文件和子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26831467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com