有时候,需要截取字符串中的两个特定字符之间的字符串,啥意思呢?
举个例子,需要截取目录"/home/book/temp/hello.c"
中的hello
,有人会说了,直接使用hello
不就得了,咱也想直接用啊,当你只有这一个文件的时候确实可以这样,若是读取目录下的所有文件并截取文件名,那不就歇菜了!
思路:给定路径 "../../sample/data/FaceFeaturelib.dat"
,如果要截取文件名,会发现FaceFeaturelib
左边一个/
右边一个.
,那就根据这两个特点来取,使用get_pos
来获取两个字符的位置,再用strncpy
按指定字节数拷贝就行了
以下为实验目录下的文件名,我们要做的就是要提取该目录下的所有文件名,不包括后缀
./
../
cvaux.h
cvaux.hpp
cv.h
cv.hpp
cvwimage.h
cxcore.h
cxcore.hpp
cxeigen.hpp
cxmisc.h
highgui.h
ml.h
代码:
#include <dirent.h>
#include <string.h>
#include <stdio.h>
int get_pos(const char *str, const char *dst)
{
const unsigned char *s1 = (const unsigned char *)str;
const unsigned char *s2 = (const unsigned char *)dst;
int delta = 0;
int count = 0;
//获得s1的长度
int length = strlen(s1);
int tmp_val = length;
//指针移动到s1结尾,从后向前查找,为啥呢?因为有的文件名不止一个 "."
while(--length)
{
s1++;
}
//查找到就返回dst所在字符串的序号,如"test.c",查找 ".",就返回数字5
while (*s1 || *s2) {
delta = *s1 - *s2;
count++;
if (!delta)
return tmp_val-count+1;
s1--;
}
return 0;
}
int main()
{
char path[] = "/home/nfs/opencv3/include/opencv/";
char name[20] = {0};
//以下是目录读取操作,会用就行
struct dirent *in_path;
DIR *dirp = opendir(path);
while((in_path = readdir(dirp)) != NULL)
{
//in_path->d_name就是目录下的文件名,其本质是个数组
//此处是把当前目录下的两个目录 "." ".." 排除掉
if (!strncmp(in_path->d_name, ".", 1) || !strncmp(in_path->d_name, "..", 2))
{
continue;
}
int pos1 = get_pos(in_path->d_name, ".");//获取 "." 在完整文件名的下标
strncpy(name, in_path->d_name, pos1-1);//拷贝文件名,截止到字符 "."
printf("all name = %s\n", in_path->d_name);//打印完整文件名
printf("name = %s\n", name);//打印不带后缀的文件名
printf("\n");
memset(name, 0, 20);
}
return 0;
}
结果如下:
all name = cvwimage.h
name = cvwimage
all name = cxcore.hpp
name = cxcore
all name = cxcore.h
name = cxcore
all name = cvaux.h
name = cvaux
all name = cxmisc.h
name = cxmisc
all name = cxeigen.hpp
name = cxeigen
all name = cv.h
name = cv
all name = highgui.h
name = highgui
all name = ml.h
name = ml
all name = cvaux.hpp
name = cvaux
all name = cv.hpp
name = cv
我的需求:只取文件名,而in_path->d_name
就是文件名,并不包含路径,所以我不必判断/
,只需要判断.
的下标
如果你需要取"../../sample/data/FaceFeaturelib.dat"
中的文件名和它上级目录,即/data/FaceFeaturelib
,也可以使用get_pos
获取倒数第二个/
和最后一个.
,然后根据两者之间的字符数量使用strncpy
就好啦。
不过这里get_pos
只实现了倒着查找,然后遇到要第一个查找的字符就返回其下标,并没有判断是第几个字符。如果需要判断倒数第二个或第三个,就需要你自己来实现啦,其实加个标志位应该就行了,到时候你需要用到strrchr
//获取文件最后出现 . 的位置,返回值是指针
file_pos = strrchr(in_path->d_name, '.');
其实下面这段是不严谨的,执行s1--;
并没有判断s1
是否越界,使用的时候自行判断吧!
while (*s1 || *s2)
...
s1--;
如有其它错误,欢迎指出!