如何检查文件夹是否为空?

问题描述 投票:0回答:1

我正在用 C 编写一个游戏,其中涉及帐户系统(作为最终项目)。我想检查

accounts
文件夹是否为空,这样我可以让玩家选择一个帐户或创建一个帐户。但我不太清楚该怎么做。

bool isFolderEmpty(const char *path) {
    WIN32_FIND_DATA findFileData;
    HANDLE hFind = FindFirstFile(path, &findFileData);

    if (hFind == INVALID_HANDLE_VALUE) {
        perror("Unable to open directory");
        return false;
    }

    bool isEmpty = true;

    do {
        if (strcmp(findFileData.cFileName, ".") != 0 &&
            strcmp(findFileData.cFileName, "..") != 0) {
            isEmpty = false;
            break;
        }
    } while (FindNextFile(hFind, &findFileData) != 0);

    FindClose(hFind);
    return isEmpty;
}

我已经尝试过ChatGPT给我的这个功能,以及ChatGPT给我的所有其他版本。但似乎

hFind
始终是
INVALID_HANDLE_VALUE
,而我确信该文件夹存在并包含一个虚拟
txt
文件。

这些在我的

main()
功能中:

system("dir");
    
if (isFolderEmpty("./accounts")) {
    return 0;
}
else {
    printf("letgo");
}

控制台显示:

2023/11/15  10:58    <DIR>          accounts

所以

accounts
文件夹确实存在。

c file winapi user-accounts
1个回答
0
投票

如果仅使用 c 不是目标 @回声关闭

dir /b /s /a-d "accounts" | findstr .>nul && (
    dir /b /a-d "accounts" > log\accountDATA.txt
echo Folder is NOT empty, file names written to log\accountDATA.txt
) || (
    >log\accountDATA.txt (
        echo. 
    )
    echo Folder is empty, accountDATA.txt cleared
)

使用批处理可能更简单直接,将路径更改为您需要的路径并使用 system() 来运行它,它将完成工作

© www.soinside.com 2019 - 2024. All rights reserved.