【c++基础】遍历目录并写入txt文件-linux

本文展示了一种使用C++编程语言从特定目录下收集所有文件名并将其写入训练数据文件的方法,适用于图像识别等机器学习项目的数据预处理阶段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

 

/******************************************************************************
* File: get_traindata.cpp
* Coder: AMY
* Email: happyamyhope@163.com
* Data: 20181107
*******************************************************************************/
#include <iostream>  
#include <stdio.h>  
#include <unistd.h>  
#include <dirent.h>  
#include <stdlib.h>  
#include <sys/stat.h>  
#include <string.h>  
#include <fstream>

//Global Variables.
char dir[100] = "/trainimg/right_eye/";  
int const MAX_STR_LEN = 200;  
std::ofstream traindata;
//Show all files under dir_name, do not show directories.  
void showAllFiles(const char* dir_name)  
{
     std::string path(dir_name);//or path = dir_name;
    //check the parameter.
    if( NULL==dir_name )  
    {  
        std::cout << "dir_name is null..." << std::endl;  
        return;  
    }  
    //check if dir_name is a valid dir.  
    struct stat s;  
    lstat(dir_name, &s);  
    if( !S_ISDIR(s.st_mode) )  
    {  
        std::cout << "dir_name is not a valid directory..." << std::endl;  
        return;  
    }  
    struct dirent* filename;//return value for readdir().  
    DIR* dir;//return value for opendir().  
    dir = opendir(dir_name);  
    if( NULL==dir )  
    {  
        std::cout << "Can not open dir..." << dir_name << std::endl;  
        return;  
    }  
    std::cout << "Successfully opened the dir..." << std::endl;  
    //read all the files in the dir. 
    while( (filename=readdir(dir)) != NULL )  
    {  
        //get rid of "." and ".."  
        if( strcmp(filename->d_name, ".")==0 || strcmp(filename->d_name, "..")==0 )  continue;  
        std::cout << filename->d_name << std::endl;  
        traindata << path+filename->d_name << std::endl;
        traindata << 1 << std::endl;
    }  
}   

int main()  
{  
    traindata.open("traindata.txt", std::ios::app);
    showAllFiles(dir);  
    traindata.close();
    return 0;  
}
View Code

 

参考

1.

https://www.itency.com/topic/show.do?id=310867

转载于:https://www.cnblogs.com/happyamyhope/p/9923756.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值