欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > c/c++ >内容正文

c/c++

C++ 从文件夹中读取文件

发布时间:2023/12/4 c/c++ 66 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C++ 从文件夹中读取文件 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

OpenCV从文件夹中读取内含文件方法

参考:http://www.2cto.com/kf/201407/316515.html

http://www.it610.com/article/5126146.htm

http://blog.csdn.net/adong76/article/details/39432467

windows平台代码:

[cpp] view plaincopy
  • #include <io.h>  
  • #include <fstream>  
  • #include <string>  
  • #include <vector>  
  • #include <iostream>  
  •  using namespace std;  
  •   
  •   
  • //获取所有的文件名  
  • void GetAllFiles( string path, vector<string>& files)    
  • {    
  •   
  •     long   hFile   =   0;    
  •     //文件信息    
  •     struct _finddata_t fileinfo;    
  •     string p;    
  •     if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) !=  -1)    
  •     {    
  •         do    
  •         {     
  •             if((fileinfo.attrib &  _A_SUBDIR))    
  •             {    
  •                 if(strcmp(fileinfo.name,".") != 0  &&  strcmp(fileinfo.name,"..") != 0)    
  •                 {  
  •                     files.push_back(p.assign(path).append("\\").append(fileinfo.name) );  
  •                     GetAllFiles( p.assign(path).append("\\").append(fileinfo.name), files );   
  •                 }  
  •             }    
  •             else    
  •             {    
  •                 files.push_back(p.assign(path).append("\\").append(fileinfo.name) );    
  •             }   
  •   
  •         }while(_findnext(hFile, &fileinfo)  == 0);    
  •   
  •         _findclose(hFile);   
  •     }   
  •   
  • }    
  •   
  • //获取特定格式的文件名  
  • void GetAllFormatFiles( string path, vector<string>& files,string format)    
  • {    
  •     //文件句柄    
  •     long   hFile   =   0;    
  •     //文件信息    
  •     struct _finddata_t fileinfo;    
  •     string p;    
  •     if((hFile = _findfirst(p.assign(path).append("\\*" + format).c_str(),&fileinfo)) !=  -1)    
  •     {    
  •         do    
  •         {      
  •             if((fileinfo.attrib &  _A_SUBDIR))    
  •             {    
  •                 if(strcmp(fileinfo.name,".") != 0  &&  strcmp(fileinfo.name,"..") != 0)    
  •                 {  
  •                     //files.push_back(p.assign(path).append("\\").append(fileinfo.name) );  
  •                     GetAllFormatFiles( p.assign(path).append("\\").append(fileinfo.name), files,format);   
  •                 }  
  •             }    
  •             else    
  •             {    
  •                 files.push_back(p.assign(path).append("\\").append(fileinfo.name) );    
  •             }    
  •         }while(_findnext(hFile, &fileinfo)  == 0);    
  •   
  •         _findclose(hFile);   
  •     }   
  • }   
  •   
  • // 该函数有两个参数,第一个为路径字符串(string类型,最好为绝对路径);  
  • // 第二个参数为文件夹与文件名称存储变量(vector类型,引用传递)。  
  • // 在主函数中调用格式(并将结果保存在文件"AllFiles.txt"中,第一行为总数):  
  •   
  • int main()  
  • {  
  •     string filePath = "testimages\\water";    
  •     vector<string> files;    
  •     char * distAll = "AllFiles.txt";  
  •   
  •     //读取所有的文件,包括子文件的文件  
  •     //GetAllFiles(filePath, files);  
  •   
  •     //读取所有格式为jpg的文件  
  •     string format = ".jpg";  
  •     GetAllFormatFiles(filePath, files,format);  
  •     ofstream ofn(distAll);  
  •     int size = files.size();   
  •     ofn<<size<<endl;  
  •     for (int i = 0;i<size;i++)    
  •     {    
  •         ofn<<files[i]<<endl;   
  •         cout<< files[i] << endl;  
  •     }  
  •     ofn.close();  
  •     return 0;  
  • }  

  • Linux平台代码:

    [cpp] view plaincopy
  • //LINUX/UNIX c获取某个目录下的所有文件的文件名  
  •    
  • #include <stdio.h>  
  • #include <dirent.h>  
  • int main(int argc, char * argv[])  
  • {  
  •     struct dirent *ptr;      
  •     DIR *dir;  
  •     dir=opendir("./file");  
  •     printf("文件列表:\n");  
  •     while((ptr=readdir(dir))!=NULL)  
  •     {  
  •    
  •         //跳过'.'和'..'两个目录  
  •         if(ptr->d_name[0] == '.')  
  •             continue;  
  •         printf("%s\n",ptr->d_name);  
  •     }  
  •     closedir(dir);  
  •     return 0;  
  • }  

  • C++ 版本

    [cpp] view plaincopy
  • #include <iostream>  
  • #include <vector>  
  • #include <string>  
  • #include <dirent.h>  
  • using namespace std;  
  •   
  • int main(int argc, char * argv[])  
  • {  
  •     struct dirent *ptr;      
  •     DIR *dir;  
  •     string PATH = "./file";  
  •     dir=opendir(PATH.c_str());   
  •     vector<string> files;  
  •     cout << "文件列表: "<< endl;  
  •     while((ptr=readdir(dir))!=NULL)  
  •     {  
  •    
  •         //跳过'.'和'..'两个目录  
  •         if(ptr->d_name[0] == '.')  
  •             continue;  
  •         //cout << ptr->d_name << endl;  
  •         files.push_back(ptr->d_name);  
  •     }  
  •       
  •     for (int i = 0; i < files.size(); ++i)  
  •     {  
  •         cout << files[i] << endl;  
  •     }  
  •   
  •     closedir(dir);  
  •     return 0;  
  • }  
  • _finddata_t 的使用  


    那么到底如何查找文件呢?我们需要一个结构体和几个大家可能不太熟悉的函数。这些函数和结构体在<io.h>的头文件中,结构体为struct _finddata_t ,函数为_findfirst、_findnext和_fineclose。具体如何使用,我会慢慢讲来~
            首先讲这个结构体吧~ struct _finddata_t ,这个结构体是用来存储文件各种信息的。说实话,这个结构体的具体定义代码,我没有找到,不过还好,文档里面在_find里有比较详细的成员变量介绍。我基本上就把文档翻译过来讲吧:


            unsigned atrrib:文件属性的存储位置。它存储一个unsigned单元,用于表示文件的属性。文件属性是用位表示的,主要有以下一些:_A_ARCH(存档)、_A_HIDDEN(隐藏)、_A_NORMAL(正常)、_A_RDONLY(只读)、_A_SUBDIR(文件夹)、_A_SYSTEM(系统)。这些都是在<io.h>中定义的宏,可以直接使用,而本身的意义其实是一个无符号整型(只不过这个整型应该是2的几次幂,从而保证只有一位为1,而其他位为0)。既然是位表示,那么当一个文件有多个属性时,它往往是通过位或的方式,来得到几个属性的综合。例如只读+隐藏+系统属性,应该为:_A_HIDDEN | _A_RDONLY | _A_SYSTEM 。

           time_t time_create:这里的time_t是一个变量类型(长整型?相当于long int?),用来存储时间的,我们暂时不用理它,只要知道,这个time_create变量是用来存储文件创建时间的就可以了。


            time_t time_access:文件最后一次被访问的时间。


            time_t time_write:文件最后一次被修改的时间。


            _fsize_t size:文件的大小。这里的_fsize_t应该可以相当于unsigned整型,表示文件的字节数。


            char name[_MAX_FNAME]:文件的文件名。这里的_MAX_FNAME是一个常量宏,它在<stdlib.h>头文件中被定义,表示的是文件名的最大长度。


            以此,我们可以推测出,struct _finddata_t ,大概的定义如下:


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


            前面也说了,这个结构体是用来存储文件信息的,那么如何把一个硬盘文件的文件信息“存到”这个结构体所表示的内存空间里去呢?这就要靠_findfirst、_findnext和_fineclose三个函数的搭配使用了。


            首先还是对这三个函数一一介绍一番吧……


            long _findfirst( char *filespec, struct _finddata_t *fileinfo );


            返回值:如果查找成功的话,将返回一个long型的唯一的查找用的句柄(就是一个唯一编号)。这个句柄将在_findnext函数中被使用。若失败,则返回-1。


            参数:


            filespec:标明文件的字符串,可支持通配符。比如:*.c,则表示当前文件夹下的所有后缀为C的文件。


            fileinfo :这里就是用来存放文件信息的结构体的指针。这个结构体必须在调用此函数前声明,不过不用初始化,只要分配了内存空间就可以了。函数成功后,函数会把找到的文件的信息放入这个结构体中。


            int _findnext( long handle, struct _finddata_t *fileinfo );


            返回值:若成功返回0,否则返回-1。


            参数:


            handle:即由_findfirst函数返回回来的句柄。


            fileinfo:文件信息结构体的指针。找到文件后,函数将该文件信息放入此结构体中。


           int _findclose( long handle );


            返回值:成功返回0,失败返回-1。

            参数:


            handle:即由_findfirst函数返回回来的句柄。


            fileinfo:文件信息结构体的指针。找到文件后,函数将该文件信息放入此结构体中。


           int _findclose( long handle );


            返回值:成功返回0,失败返回-1。


            参数:


            handle :_findfirst函数返回回来的句柄。


            大家看到这里,估计都能猜到个大概了吧?先用_findfirst查找第一个文件,若成功则用返回的句柄调用_findnext函数查找其他的文件,当查找完毕后用,用_findclose函数结束查找。恩,对,这就是正确思路。下面我们就按照这样的思路来编写一个查找C:\WINDOWS文件夹下的所有exe可执行文件的程序。


            #include <stdio.h>
            #include <io.h>


            const char *to_search="C:\\WINDOWS\\*.exe";        //欲查找的文件,支持通配符


            int main()
            {
                 long handle;                                                //用于查找的句柄
                 struct _finddata_t fileinfo;                          //文件信息的结构体
                 handle=_findfirst(to_search,&fileinfo);         //第一次查找
                 if(-1==handle)return -1;
                 printf("%s\n",fileinfo.name);                         //打印出找到的文件的文件名
                 while(!_findnext(handle,&fileinfo))               //循环查找其他符合的文件,知道找不到其他的为止
                 {
                      printf("%s\n",fileinfo.name);
                }
                 _findclose(handle);                                      //别忘了关闭句柄
                 system("pause");
                 return 0;
            }


            当然,这个文件的查找是在指定的路径中进行,如何遍历硬盘,在整个硬盘中查找文件呢?大家可以在网络上搜索文件递归遍历等方法,这里不再做进一步介绍。

            程序的末尾用了一个system函数。这个与程序本身并没有影响,和以前介绍给大家的使用getchar()函数的作用相同,只是为了暂停一下,让我们能看到命令提示符上输出的结果而已。不过system函数本身是一个非常强大的函数。大家可以查查MSDN看看~ 简单来说,它是一个C语言与操作系统的相互平台,可以在程序里通过这个函数,向操作系统传递command

    总结

    以上是生活随笔为你收集整理的C++ 从文件夹中读取文件的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。