【问题标题】:How do I print only the file part of a full pathname?如何仅打印完整路径名的文件部分?
【发布时间】:2020-12-19 01:01:50
【问题描述】:

以下是我所面临问题的快速重现:

#include <iostream>
#include <cstring>

int main()
{
    char path[100] = "home/user/cvs/test/VSCode/Test.dll";
    char *pos = strrchr(path, '/');
if (pos != NULL) 
{
   *pos = '\0'; 
}
    printf("%s", path);
}

我在路径名中找到最后一个“/”,需要打印最后一个“/”之后的所有内容,所以输出需要是:

Test.dll

但是,使用我当前的代码,输出是:

home/user/cvs/test/VSCode

基本上我的代码打印最后一个“/”之前的所有内容,但我需要打印最后一个“/”之后的所有内容。

【问题讨论】:

  • 您可以使用printf("%s", pos + 1);(并省略*pos = '\0')。另外,我会做char path[] = "home/user/cvs/test/VSCode/Test.dll";(省略数组大小,因为编译器会推断它)。
  • \0 代表一个字符串的结尾,这就是为什么你要更新到最后一个 / 因为你正在更新它到 \0

标签: c++ c printf substring


【解决方案1】:

在调用strrchr 之后,pos 将指向最后一次出现的/。如果你提前一位,它将指向文件名的开头:

char *pos = strrchr(path, '/');
if (pos != NULL) 
{
   ++pos; 
   printf("%s", pos); /* Note - printing pos, not path! */
}

【讨论】:

  • 谢谢你这是完美的!!
  • 如果pos NULL (意味着没有/ 字符)您应该将其设置为path 并将printf 移出测试。
猜你喜欢
  • 2022-07-15
  • 2015-11-26
  • 1970-01-01
  • 2020-08-30
  • 2012-03-01
  • 1970-01-01
  • 2021-09-01
  • 2011-07-04
  • 2014-04-25
相关资源
最近更新 更多