linux下遍历文件夹及获取路径下文件名字(字符串操作)

因为最近在做LPR(车牌识别)的小项目,需要把图片样本导入并训练,所以写了一个小程序。

在参考了网上部分资料后,得到目标目录charSamples下,文件夹1里所有50个样本图片文件的路径。

------------------------------------------------------------------

1.dirent.h
dirent,LINUX系统下的一个头文件,在这个目录下/usr/include,为了获取某文件夹目录内容,所使用的结构体。

引用头文件#include<dirent.h>

struct dirent

{


long d_ino;/* inode number 索引节点号 */
off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
unsigned short d_reclen;/* length of this d_name 文件名长 */
unsigned char d_type;/* the type of d_name 文件类型 */
char d_name [NAME_MAX+1];/* file name (null-terminated) 文件名,最长256字符 */
}

-------------------------------------------------------------------

2.实现过程
这是我保存的图片路径图:

 

 

--------------------------------------------------------------------------------------------------------------

执行效果:

 

 

3.程序附录

 

#include <dirent.h>
#include <stdio.h>
#include<iostream>
#include<vector>
using namespace std;
vector <string> findfile(string path);
int main(int argc, char *argv[])
{
    vector<string> Filename = findfile("charSamples/1/");
}
vector <string> findfile(string path)
{
    DIR *dp;
    struct dirent *dirp;
    vector<std::string> filename;
    if( (dp=opendir(path.c_str()) )==NULL )
        perror("open dir error");
    while( (dirp=readdir(dp) )!=NULL )
    filename.push_back(path + string(dirp->d_name));
    for (int i = 2;i<filename.size();i++)
        cout<<i<<":"<<filename[i]<<endl;
    closedir(dp);
    return filename;
}

  

有点疑惑:输出的时候,我是以 I = 2 为起始的,因为 I= 0和1 的时候输出的是一个“.”符号,不知道为什么。

最后,图片文件是这样的,其他文件也应该差不多,大家可以多试试。

 

目的:从完整路径中提取文件名、不带后缀的名字、后缀名

如下:

#include <iostream>  
#include <string> 
using namespace std;
void main()
{
	string path = "C:\Users\Administrator\Desktop\text\data.22.txt";
	
	//1.获取不带路径的文件名
	string::size_type iPos = path.find_last_of('\') + 1;
	string filename = path.substr(iPos, path.length() - iPos);
	cout << filename << endl;
 
	//2.获取不带后缀的文件名
	string name = filename.substr(0, filename.rfind("."));
	cout << name << endl;
 
	//3.获取后缀名
	string suffix_str = filename.substr(filename.find_last_of('.') + 1);
	cout << suffix_str << endl;
}

  

 

posted @ 2022-03-25 16:04  小丑_jk  阅读(2812)  评论(0编辑  收藏  举报