只读目录下的.txt文件,该目录也有子文件夹
read only .txt files from directory which has subfolders too
我正试图从目录中读取。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;
}
相关文章:
- 如何将更多文件夹添加到c++include路径
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何在文档文件夹中创建目录
- "assimp/config.h"找不到,但它在文件夹中
- C++入门 5 版:类消息和文件夹
- 我可以在 Arduino 的库文件夹之外安装库吗?
- 如何按文件扩展名引用文件夹中的文件
- 在QTreeView中仅显示共享驱动器和文件夹
- 加载与引用 .NET DLL 位于同一文件夹中的引用的 .NET DLL 时"Not found"异常
- 介子复制/安装头文件到输出目录并保持文件夹结构
- vcruntime.h 从 Windows 包含文件夹中丢失?
- 在文件夹迭代上实现 RAII
- 使用 Powershell 命令将 cpp 文件的文件夹编译为 GNU 的 g++
- 使文件夹中的所有文件可供所有项目(子目录)访问
- 无法使用 CMake 从其他文件夹添加源文件
- 如何在安卓工作室中将c ++头文件从一个文件夹导入到另一个文件夹?
- 对单元测试(googletest)和项目/文件夹/文件的混淆
- 设计文件夹/文件系统