【问题标题】:Find absolute path in linux using strchr在linux中使用strchr查找绝对路径
【发布时间】:2021-08-27 05:29:34
【问题描述】:

如何使用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

【问题讨论】:

  • 从手册页引用:strchr() 函数返回一个指针,指向字符串 s 中字符 c 的第一次出现。 第一次出现在最左边,这是第一个字符。
  • 您使用了错误的术语。从技术上讲,您正在寻找的是路径名前缀。
  • 从代码示例看来,您实际上并不想要绝对路径。如果您确实想要绝对路径,请尝试realpath

标签: c linux path strchr


【解决方案1】:

改用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 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多