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 2022-05-07 09:54  飘杨......  阅读(516)  评论(0编辑  收藏  举报