C++从一个文件夹中读出所有txt文件的方法示例

发布时间:2020-10-03 21:35:33 作者:Hahallo
来源:脚本之家 阅读:327

前言

前段时间做项目需要读取一个文件夹里面所有的txt文件,查询资料后得到以下实现方法:

首先了解一下这个结构体

struct _finddata_t {
 unsigned attrib;
 time_t time_create; 
 time_t time_access; 
 time_t time_write;
 _fsize_t size;
 char name[260];
};

其中各成员变量的含义如下:

查找文件需要用到_findfirst 和 _findnext 两个函数,这两个函数包含在io.h库中

1、_findfirst函数:long _findfirst(const char *, struct _finddata_t *);

第一个参数为文件名,可以用"*.*"来查找所有文件,也可以用"*.cpp"来查找.cpp文件。第二个参数是_finddata_t结构体指针。若查找成功,返回文件句柄,若失败,返回-1。

2、_findnext函数:int _findnext(long, struct _finddata_t *);

第一个参数为文件句柄,第二个参数同样为_finddata_t结构体指针。若查找成功,返回0,失败返回-1。

3、_findclose()函数:int _findclose(long);

只有一个参数,文件句柄。若关闭成功返回0,失败返回-1。

代码及实现

需要输出的文件

C++从一个文件夹中读出所有txt文件的方法示例

运行结果

C++从一个文件夹中读出所有txt文件的方法示例

代码

#include <iostream>
#include <string> 
#include <fstream> 
#include <io.h>
using namespace std
void GetLineAndPrint(string in_name)
{
 ifstream fin(in_name);
 if (!fin)
 {
 cerr << "open file error" << endl;
 exit(-1);
 }
 string str;
 while (getline(fin, str))
 {
 cout << str << endl;
 }
}
int main()
{
 struct _finddata_t fileinfo;
 string in_path;
 string in_name;
 cout << "输入文件夹路径:" ;
 cin >> in_path;
 string curr = in_path + "\\*.txt";
 long handle;
 if ((handle = _findfirst(curr.c_str(), &fileinfo)) == -1L)
 {
 cout << "没有找到匹配文件!" << endl;
 return 0;
 }
 else
 {
 in_name = in_path + "\\" + fileinfo.name;
 GetLineAndPrint(in_name);
 while (!(_findnext(handle, &fileinfo)))
 {
 in_name = in_path + "\\" + fileinfo.name;
 GetLineAndPrint(in_name);
 }
 _findclose(handle);
 }
}

注:代码在vs2017中编译通过。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对亿速云的支持。

参考资料:https://www.jb51.net/article/142285.htm

原文链接:https://www.cnblogs.com/bigyang/p/8547038.html

推荐阅读:
  1. 快速从一个XML文件中查找信息的方法
  2. python或C++读取指定文件夹下的所有图片

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++ 文件夹 txt文件

上一篇:java实现点击按钮事件弹出子窗口

下一篇:Spring boot @RequestBody数据传递过程详解

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》