随笔 - 632  文章 - 17  评论 - 54  阅读 - 93万

C/C++使用ofstream遍历目录并将目录中的文件路径写入文件中

一、概述

  案例:实现一个小功能,遍历文件目录并将目录下的文件路径写入一个文件中。做这个小功能是为了OpenCV的人脸识别准备数据。(文件路径后面跟上文件所对应的标签)

  需要导入的头文件:

复制代码
#include <fstream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
主要使用到的函数及方法:
1.DIR:opendir、dirent、readdir、ofstream等
复制代码

 

二、代码示例

 使用步骤:
ofstream out;
string filename = string("/Users/yangwei/Documents/tony/opencv/orl_faces/targetData.txt");
            out.open(filename,ios::out);
            prepareImageData(srcDirPath.toStdString().c_str(),"");
            out.close();
复制代码
/**
 * 准备人脸数据
 * 将人脸数据写入txt文件中
 * @brief Face_Eigen_Face_Recognizer::prepareImageData
 */
void Face_Eigen_Face_Recognizer::prepareImageData(const char * dirPath,char *appStr){
    DIR *pDir;
    struct dirent *ptr;
    if(!(pDir=opendir(dirPath))){
        qDebug()<<"Folder doesn't Exist!";
        return;
    }
    while((ptr=readdir(pDir))!=0){
        if(strcmp(ptr->d_name,".")!=0&&strcmp(ptr->d_name,"..")!=0){
            char resultStr[100];
            sprintf(resultStr,"%s%s",dirPath,ptr->d_name);

            struct stat s;
            if(stat(resultStr,&s)==0){//路径存在
                if(s.st_mode&S_IFDIR){//文件夹
                    char *dirName = ptr->d_name;
                    char targetName[5];
                    memcpy(targetName,dirName+1,strlen(dirName));
                    cout <<"dirName:"<<dirName<< "--->targetName:"<<targetName<<endl;
                    prepareImageData(resultStr,targetName);
                }
            }else{
                sprintf(resultStr,"%s/%s",dirPath,ptr->d_name);
                //                cout << resultStr<<endl;
                //                cout <<"error"<<endl;
                //将得到的数据存储到txt文件中
                if(out.is_open()){//此处的out为ofstream,由其open函数来提供初始化
                    out << resultStr <<" "<<appStr<<endl;
                }else{
                    cout <<"file is not opened"<<endl;
                }

            }

        }
    }
    closedir(pDir);
}
复制代码

 

三、演示图片

 

posted on   飘杨......  阅读(576)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示