【发布时间】:2015-04-06 02:14:26
【问题描述】:
我想保存字符串中的最后一个字符?关于如何做到这一点的任何想法?
目标:我目前正在编写一个程序,其中一项任务是使用 Unix / POSIX 搜索文件扩展名。例如,如果用户输入:
./r_client localhost -name '*.c'
它应该返回所有名称为 .c 文件扩展名类型的文件。因此,我正在考虑将最后一个 char strcat 抓取到以下代码中
然后搜索我的目录如下:
下面是使用正则表达式的示例代码
#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
int main(int argc, char *argv[]){
regex_t regex;
int reti;
char msgbuf[100];
char *name = "*.c";
// grab last char, strcat it to -> "[a-zA-Z0-9]\.c$"
// because it could be '.h', '.x', etc.
/* Compile regular expression */
reti = regcomp(®ex, "[a-zA-Z0-9]\.c$", 0);
if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }
/* Execute regular expression */
reti = regexec(®ex, "e09s*fdf.ec", 0, NULL, 0);
if( !reti ){
puts("Match");
}
else if( reti == REG_NOMATCH ){
puts("No match");
}
else{
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
/* Free compiled regular expression if you want to use the regex_t again */
regfree(®ex);
return 0;
}
// 然后调用 ("e09s*fdf.ec" - 这是一个测试) - 它应该如何失败 w/.c
reti = regexec(®ex, "e09s*fdf.ec", 0, NULL, 0);
将被替换为:dir_entry->d_name
除非有更好的方法来做到这一点?
提前感谢您的帮助
【问题讨论】:
-
文件名是否支持 shell glob?如果这是您想要做的,请使用
glob()或wordexp()。无需重新发明轮子。