在一个C程序中,我有一个字符串表示的文件路径(具体来说是存储在argv[0]
中的exe
名称)。我想提取文件名并且舍弃目录路径,使用MS Visual Studio 2005。是否有任何内置函数可以实现这一功能?
供参考,这是我实现的代码,据说可以在Win/Unix上兼容:
char *pfile;
pfile = argv[0] + strlen(argv[0]);
for (; pfile > argv[0]; pfile--)
{
if ((*pfile == '\\') || (*pfile == '/'))
{
pfile++;
break;
}
}
其实不用,只需定位路径中最后一个反斜杠即可。反斜杠后面的所有内容都是文件名,如果没有则表示路径指定了目录名。
// Returns filename portion of the given path
// Returns empty string if path is directory
char *GetFileName(const char *path)
{
char *filename = strrchr(path, '\\');
if (filename == NULL)
filename = path;
else
filename++;
return filename;
}
#include <unistd.h>
char * basename (const char *fname);
glibc
也定义并初始化了program_invocation_short_name
变量。 - ysapchar *p, *s = args[0]; // or any source pathname
...
p = strchr(s, '\\'); // find the 1st occurence of '\\' or '/'
// if found repeat the process (if not, s already has the string)
while(p) {
s = ++p; // shift forward s first, right after '\\' or '/'
p = strchr(p, '\\'); // let p do the search again
}
// s now point to filename.ext
...
_TCHAR
,请使用 _tcschr
而不是 strchr
strchr
的作用类似于:while((*p) && (*p != '\\')) p++;
如果未找到 chr
,则会返回安全带 NULL。
因此,如果您真的不想依赖另一个库,可以使用这个方法。char *p, *s = args[0];
...
p = s; // assign to s to p
while(*p && (*p != '\\')) p++;
while(*p) { // here we have to peek at char value
s = ++p;
while (*p && (*p != '\\')) p++;
}
// s now point to filename.ext
...
asm
。
const
。 - unwind