【问题标题】:How to extract a file name from a full path如何从完整路径中提取文件名
【发布时间】:2011-05-05 17:12:09
【问题描述】:

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

【问题讨论】:

    标签: c filenames


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 谢谢,@乔纳森。是的,这是显而易见的方式。我认为可能有一个现成的功能可以节省我的编码工作。
      • 这里应该有更多const。
      • ... 这是我想避免的问题——这段代码是特定于 Windows 的。在 Unix b/c 上不起作用,斜杠应该是反斜杠。无论如何,为代码坦克。
      【解决方案3】:

      如果你想要一个来自 libc 的函数:

      #include <unistd.h>
      
      char * basename (const char *fname);
      

      【讨论】:

      • 谢谢,很好的发现。尽管根据手册页,当尾部有斜杠时,POSIX 版本的意义不如 GNU 版本。此功能是否与 Windows 兼容(即 MSVC 是否支持此功能,并且它是否识别反斜杠)?
      • 是的,我相信the documentation 说它将正斜杠和反斜杠视为分隔符。
      • 当我们在 GNU 时,glibc 也定义并初始化了 program_invocation_short_name 变量。
      【解决方案4】:

      这是穷人的版本:

      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) &amp;&amp; (*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..

      【讨论】:

      • 谢谢。那是很久以前的事了……您的代码可能在 Windows 上工作,但在 Unix 上会失败。查看其他答案。
      【解决方案5】:
      猜你喜欢
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 2018-04-21
      相关资源
      最近更新 更多