C++从一个文件夹中读出所有txt文件的方法示例
前言 前段时间做项目需要读取一个文件夹里面所有的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函数: 第一个参数为文件名,可以用"*.*"来查找所有文件,也可以用"*.cpp"来查找.cpp文件。第二个参数是_finddata_t结构体指针。若查找成功,返回文件句柄,若失败,返回-1。 2、_findnext函数: 第一个参数为文件句柄,第二个参数同样为_finddata_t结构体指针。若查找成功,返回0,失败返回-1。 3、_findclose()函数: 只有一个参数,文件句柄。若关闭成功返回0,失败返回-1。 代码及实现 需要输出的文件 运行结果 代码 #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中编译通过。 总结 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对编程小技巧的支持。 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |