只读目录下的.txt文件,该目录也有子文件夹

read only .txt files from directory which has subfolders too

本文关键字:文件夹 文件 txt 只读      更新时间:2023-10-16

我正试图从目录中读取。txt文件。我没有使用数组。我用opendir()打开我的目录。d->d_name列出了我所有的文件和子文件夹。我只想读.txt,而不是子文件夹。

请帮帮我。由于

可以不使用FindFirstFile和FindNextFile吗?

比如:

    调用opendir()打开目录
  • 在循环中,调用readdir读取每个
  • 条目
  • 对于每个条目,检查名称以查看最后4个字符是否为".txt"
  • 如果是,做点什么
  • 结尾,调用closedir关闭
  • 目录

您可以使用stat()函数来确定struct dirent所代表的文件类型。

struct stat sb;
int rc = stat(filename, &sb);
// error handling if stat failed
if (S_ISREG(sb.st_mode)) {
 // it's a regular file, process it
} else {
 // it's not a regular file, skip it
}

详细信息请阅读手册页。还要注意d_name中的文件名不包含目录部分。如果您在与opendir 'd不同的目录中,则需要在目录名前加上目录分隔符(如果需要的话,还需要加上目录分隔符)。

有关c++的替代方案,请参见boost::filesystem。

您可以尝试将文件名放入一个简单的结构中(例如字符串数组或向量),然后将对该结构的引用传递给一个函数,该函数将删除不使用.txt扩展名的名称

中的函数,查看每个文件名(for循环会很方便),并使用String库中的find函数查看最后四个字符是否==到.txt。您可以将的位置重置为开始搜索字符串为string_name。长度- 4,以便您只比较最后几个字符。

Cplusplus.com是一个很好的参考,比如String库:http://www.cplusplus.com/reference/string/string/find/

假设您在Linux/Posix系统上,您可以使用scandir(…)。您可以在手册页上找到详细信息,但简而言之,您必须提供一个过滤器函数,该函数以不同的指针作为参数,如果要包含条目,则返回非零(在您的情况下,您将检查以.txt结尾的名称,以及不同结构中的文件类型)。

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
int main(int argc, char *argv[])
{
    DIR *dir;
    struct dirent *entry;
    int pos;
    if (argc < 2)
    {
        printf("Usage: %s <directory>n", argv[0]);
        return 1;
    }
    if ((dir = opendir(argv[1])) == NULL)
    {
        perror("opendir");
        return 1;
    }
    while ((entry = readdir(dir)) != NULL)
    {
        if (entry->d_type != DT_REG)
            continue;
        pos = strlen(entry->d_name) - 4;
        if (! strcmp(&entry->d_name[pos], ".txt"))
        {
            printf("%sn", entry->d_name);
        }
    }
    if (closedir(dir) == -1)
    {
        perror("closedir");
        return 1;
    }
    return 0;
}