使用MSVS2005从C中的完整路径提取文件名

在C程序中,我在字符串中有一个文件路径(具体来说,这是存储在argv[0]exe名称)。 我想提取文件名并使用MS Visual Studio 2005丢弃目录路径。任何内置函数?

不是真的,只需找到路径中的最后一个反斜杠。 之后的任何东西都是文件名。 如果之后没有任何内容,则路径指定目录名称。

 // 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; } 

作为参考,这是我实现的代码,据说是Win / Unix兼容的:

  char *pfile; pfile = argv[0] + strlen(argv[0]); for (; pfile > argv[0]; pfile--) { if ((*pfile == '\\') || (*pfile == '/')) { pfile++; break; } } 

如果你想从libc获得一个函数:

 #include  char * basename (const char *fname); 

这是穷人的版本:

 char *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则返回safebelt NULL返回。 所以,如果你真的不喜欢依赖另一个lib,你可以使用它:

 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代替..