问题描述
我们如何使用函数strchr
在linux中查找绝对路径,例如:
Input: /home/test/sample
Output: /home/test
我试着写这样的东西:
int main() {
char* string = "/home/test/sample";
char* pos;
pos = strchr(string,'/');
printf("%s\n",pos);
return 0;
}
但这不起作用,我得到了与输入相同的输出:
Input: /home/test/sample
Output: /home/test/sample
解决方法
改用 dirname 函数:
#include <libgen.h>
#include <stdio.h>
#include <string.h>
int main()
{
char* string = strdup ("/home/test/sample");
char* pos;
pos = dirname (string);
printf ("%s\n",pos);
return 0;
}
为了搜索最合适的出现次数,请使用 strrchr 函数。