如何只打印完整路径名的文件部分?
How do I print only the file part of a full pathname?
这里是我面临的问题的快速重现:
#include <iostream>
#include <cstring>
int main()
{
char path[100] = "home/user/cvs/test/VSCode/Test.dll";
char *pos = strrchr(path, '/');
if (pos != NULL)
{
*pos = '[=10=]';
}
printf("%s", path);
}
我在路径名中找到最后一个“/”,需要打印最后一个“/”之后的所有内容,所以输出需要是:
Test.dll
但是,使用我当前的代码,输出是:
home/user/cvs/test/VSCode
基本上我的代码打印最后一个“/”之前的所有内容,但我需要打印最后一个“/”之后的所有内容。
调用strrchr
后,pos
将指向最后一次出现的/
。如果向前移动一位,它将指向文件名的开头:
char *pos = strrchr(path, '/');
if (pos != NULL)
{
++pos;
printf("%s", pos); /* Note - printing pos, not path! */
}
这里是我面临的问题的快速重现:
#include <iostream>
#include <cstring>
int main()
{
char path[100] = "home/user/cvs/test/VSCode/Test.dll";
char *pos = strrchr(path, '/');
if (pos != NULL)
{
*pos = '[=10=]';
}
printf("%s", path);
}
我在路径名中找到最后一个“/”,需要打印最后一个“/”之后的所有内容,所以输出需要是:
Test.dll
但是,使用我当前的代码,输出是:
home/user/cvs/test/VSCode
基本上我的代码打印最后一个“/”之前的所有内容,但我需要打印最后一个“/”之后的所有内容。
调用strrchr
后,pos
将指向最后一次出现的/
。如果向前移动一位,它将指向文件名的开头:
char *pos = strrchr(path, '/');
if (pos != NULL)
{
++pos;
printf("%s", pos); /* Note - printing pos, not path! */
}