【C语言】遍历文件夹所有目录下的文件,并读取、处理与存储

#include <stdio.h> 
#include "dirent.h"  
#include <cstring>
#include <cstdlib>
#include <stdlib.h>


/*

typedef struct _Position {
    int left;
    int top;
    int right;
    int bottom;
}Position;

typedef struct _Obj_Data {
    Position pos;
    float prob;
}Obj_Data;

typedef struct {
    int id;
    Position pos;
    int reserve[4];
}Track_Info;

*/

/*
数据格式:
000001.txt
000002.txt
000003.txt


000001.txt内文件格式
left top right bottom 2048dims
left top right bottom 2048dims
left top right bottom 2048dims

 */


int main()  
{     
    //不按顺序排序进行遍历文件
    // int i = 0;
    // int filesize = 0;  
    // DIR *dir = NULL;  
    // struct dirent *entry;  
      
    // if((dir = opendir(FilePath))==NULL)  
    // {  
    //     printf("opendir failed!");  
    //     return -1;  
    // }
    // else  
    //     {  
    //          while(entry=readdir(dir))  
    //         {  
       
    //             if(!strcmp(".",entry->d_name) || !strcmp("..",entry->d_name))
    //                 continue;
                
    //             i++;
    //             printf("filename%d = %s   ",i,entry->d_name);  //输出文件或者目录的名称
    //             printf("filetype = %d\n",entry->d_type);  //输出文件类型   
    //         }  
      
    //          closedir(dir);    
    //  }  
    //  return 0;  

    ///按顺序排序进行遍历文件

    Obj_Data Detection[100];   //支持最多100个目标

    int mot_17_train[7] = {2,4,5,9,10,11,13};
    int mot_20_train[4] = {1,2,3,5};

    int mot_17_train_cnt = sizeof(mot_17_train) / sizeof(mot_17_train[0]);
    int mot_20_train_cnt = sizeof(mot_20_train) / sizeof(mot_20_train[0]);


    for(int i=0;i<mot_17_train_cnt;i++) 
    {
        char FilePath[256];
        sprintf(FilePath, "/home/ronales/mot_16_17_20data/MOT17/train/MOT17-%02d-DPM/yolox_det_reid/", mot_17_train[i]);
        printf("%s\n",FilePath );


        char ResFilePath[256];
        sprintf(ResFilePath, "/home/ronales/mot_16_17_20data/MOT17/train/MOT17-%02d-DPM/MOT17-%02d-DPM-TrackRes.txt", mot_17_train[i],mot_17_train[i]);
        printf("%s\n",ResFilePath );
        FILE *res_fp = fopen(ResFilePath,"w");

        struct dirent **namelist;
        int n;
        n = scandir(FilePath,&namelist,0,alphasort);

        char fullname[312] ="";

        if(n < 0)
        { 
            printf("No File return; total number is : %d", n );
        }
        else
        {
            int index=0;
            FILE *fp;
            int current_frame = 1;


            while(index < n)
            {
                //过滤掉目录里的. 和 ..文件名
                if(!strcmp(".",namelist[index]->d_name) || !strcmp("..",namelist[index]->d_name))
                {
                   index++; 
                   continue; 
                }

                // printf("d_ino:%ld  d_off:%ld d_name: %s\n", namelist[index]->d_ino,namelist[index]->d_off,namelist[index]->d_name);

                sprintf(fullname, "%s%s", FilePath, namelist[index]->d_name);
                printf("%s\n", fullname);


                int totalnum_perframe = 0;
                if( (fp=fopen(fullname,"rb")) == NULL )
                {
                    printf("Fail to open file!\n");
                    exit(0);  //退出程序(结束程序)
                }

                //每个文件对应该帧所有的定位信息与特征
                char delim[] = " ";
                char textline[50024];
                Obj_Data bbox[100];
                float feature[100][FEATURE_SIZE];
                Track_Info tracks[100];

                //循环读取文件的每一行数据
                while( fgets(textline, sizeof(textline), fp) != NULL ) 
                {
                    // printf("%s", textline);

                    char *token= strtok(textline,delim); 
                    bbox[totalnum_perframe].pos.left = atoi(token);

                    token = strtok(NULL, delim);   bbox[totalnum_perframe].pos.top = atoi(token);
                    token = strtok(NULL, delim);   bbox[totalnum_perframe].pos.right = atoi(token);
                    token = strtok(NULL, delim);   bbox[totalnum_perframe].pos.bottom = atoi(token);
                    token = strtok(NULL, delim);   bbox[totalnum_perframe].prob = atof(token);
  
                    for (int j = 0; j < FEATURE_SIZE; j++)
                    {
                        token = strtok(NULL, delim);
                        // printf(" %f",atof(token) );
                        feature[totalnum_perframe][j] = atof(token);
                    }

                    //当前帧检测到的目标数量
                    totalnum_perframe++;
                }
                

                printf("current number is %d \n", totalnum_perframe);
                printf("########################################\n");

                // IVS_API int IVS_CALL Get_MOT_TracksResults(IN int ch_handle, IN const Obj_Data objBuf[], IN float feature[][FEATURE_SIZE], INOUT Track_Info track[], int count);

                ///to do somethings///
                // int res_cnt = 0;
                // res_cnt = Get_MOT_TracksResults(0, bbox, feature, tracks, totalnum_perframe);


                for (int i = 0; i < totalnum_perframe ; ++i)
                {
                    tracks[i].reserve[0] = -1;
                    tracks[i].reserve[1] = -1;
                    tracks[i].reserve[2] = -1;
                    tracks[i].reserve[3] = -1;

                    int left = tracks[i].pos.left;
                    int top = tracks[i].pos.top;
                    int width = tracks[i].pos.right - tracks[i].pos.left;
                    int height = tracks[i].pos.bottom - tracks[i].pos.top;
       
                    fprintf(res_fp,"%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n" ,current_frame,tracks[i].id,left,top,width,height,tracks[i].reserve[0],tracks[i].reserve[1],tracks[i].reserve[2],tracks[i].reserve[3]);
                    
                }

                current_frame++;
                //操作结束后关闭文件
                fclose(fp);


                free(namelist[index]);
                index++;
            }
            free(namelist);
        }


        fclose(res_fp);
        //exit(0);
        

    }


}  

  • 1
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: c语言遍历文件夹的方法如下: 1. 使用opendir函数打开文件夹, 并使用readdir函数读取文件夹中的文件名。 2. 使用循环遍历文件夹中的所有文件。 3. 对于每一个文件, 使用stat函数获取文件的信息, 包括文件类型(是否是文件夹)。 4. 如果是文件夹, 递归调用此函数, 进入新的文件夹继续遍历。 5. 当文件夹遍历完毕后, 使用closedir函数关闭文件夹。 下面是一个示例代码: ``` #include <stdio.h> #include <dirent.h> #include <sys/stat.h> void listdir(const char *name) { DIR *dir; struct dirent *entry; if (!(dir = opendir(name))) return; while ((entry = readdir(dir)) != NULL) { struct stat st; char path[1024]; snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); if (lstat(path, &st) == -1) continue; if (S_ISDIR(st.st_mode)) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; printf("%*s[%s]\n", indent, "", entry->d_name); listdir(path); } else printf("%*s- %s\n", indent, "", entry->d_name); } closedir(dir); } int main() { listdir("."); return 0; } ``` 希望这个示例代码能够帮助你理解文件夹遍历的方法。 ### 回答2: 遍历文件夹指的是以某种方式遍历文件夹中的所有文件和子文件夹。在计算机编程中,常用的遍历文件夹的方法包括递归和迭代。 递归遍历文件夹是一种深度优先的方式。这种方法会从根文件夹开始,首先获取当前文件夹中的所有文件和子文件夹。然后,对于每个子文件夹,再递归调用遍历文件夹方法,重复上述步骤,直到遍历到最底层的文件夹。这种方式可以确保遍历文件夹中的每个文件和子文件夹,但可能会消耗较多的内存。 迭代遍历文件夹是一种广度优先的方式。这种方法会使用一个队列来存储遍历文件夹。开始时,将根文件夹入队。然后,从队列中取出一个文件夹,获取其中的所有文件和子文件夹,并将它们入队。重复上述步骤,直到队列为空。这种方式可以逐层遍历文件夹,较递归方式占用较少的内存。 在实际编程中,可以根据具体需求选择适合的遍历文件夹的方法。递归方式相对简单,但可能导致栈溢出或死循环等问题。迭代方式相对复杂,但可以灵活控制遍历的深度和顺序。无论选择哪种方式,遍历文件夹都是访问文件系统中重要内容的基本操作之一。 ### 回答3: 遍历文件夹是指对指定的文件夹进行逐个查找和检索其中的文件和子文件夹的过程。 在计算机编程中,实现文件夹遍历通常需要使用递归算法。具体步骤如下: 1. 首先,我们需要指定一个顶层文件夹作为起始点。可以是任意一个已存在的文件夹。 2. 然后,我们通过读取起始文件夹的内容(包括文件和子文件夹),获取这些内容的相关信息,例如文件名、文件类型、文件大小等。 3. 对于每一个子文件夹,我们将重复步骤2,进一步查找其中的文件和子文件夹。这就是递归的过程,直到遍历到最底层的文件夹。 4. 遍历文件夹的过程中,可以根据需要进行文件的筛选,例如只处理某些特定类型的文件。 5. 最后,我们可以对遍历到的每一个文件进行自定义的操作,例如打印文件路径、复制文件、修改文件等。 通过遍历文件夹,我们可以方便地获取指定文件夹下的所有文件,对其进行批量处理,例如备份、删除、搜索等。这在文件管理、数据处理和程序开发中都是常见的应用场景。 需要注意的是,对于大型文件夹或者文件夹层级很深的情况下,可能会遇到性能问题,因此在实际开发时需要进行优化,例如通过并行处理来提高遍历速度,避免资源浪费和耗时过长。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值