如何在 c++ 中获取文件后缀

How to get file suffix in c++?

本文关键字:获取 文件 后缀 c++      更新时间:2023-10-16

我想获取我知道存在于某个文件夹中的文件的后缀(.txt,.png等)。我知道文件名(前缀)在此文件夹中是唯一的。语言是 c++。

谢谢

假设"后缀"是文件扩展名,您可以这样做:

char * getfilextension(char * fullfilename)
{
   int size, index;
   size = index = 0;
   while(fullfilename[size] != '') {
      if(fullfilename[size] == '.') {
         index = size;
      }
       size ++; 
   }
   if(size && index) {
      return fullfilename + index;
   }
      return NULL;
}

它是 C 代码,但我相信可以轻松移植到 C++(也许没有变化)。

getfilextension("foo.png"); /* output -> .png */

我希望这对你有所帮助。

更新:

您将需要扫描目录的所有文件,如果等于您的目标,则比较每个没有扩展名的文件。

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <limits.h>
    #include <dirent.h>
    #include <string.h>
    //.....
    char * substr(char * string, int start, int end)
    {
       char * p = &string[start];
       char * buf = malloc(strlen(p) + 1);
       char * ptr = buf;
       if(!buf) return NULL;
       while(*p != '' && start < end) {
          *ptr ++ = *p++;
          start ++;
       }
       *ptr++ = '';
       return buf;
    }
    char * getfilenamewithoutextension(char * fullfilename)
    {
       int i, size;
       i = size = 0;
       while(fullfilename[i] != '') {
          if(fullfilename[i] == '.') {
             size = i;
          }
          i ++;
       }
       return substr(fullfilename, 0, size);
    }
    char * getfilextension(char * fullfilename)
    {
       int size, index;
       size = index = 0;
       while(size ++, fullfilename[size]) {
          if(fullfilename[size] == '.') {
             index = size;
          }
       }
       if(size && index) {
          return fullfilename + index;
       }
          return NULL;
    }
   char*FILE_NAME;
   int filefilter(const struct dirent * d)
   {
      return strcmp(getfilenamewithoutextension((char*)d->d_name), FILE_NAME) == 0;
   }

然后:

   void foo(char * path, char * target)  {
   FILE_NAME = target;
   struct dirent ** namelist;
   size_t dirscount;
   dirscount = scandir(path, &namelist, filefilter, alphasort);
   if(dirscount > 0) {
      int c;
      for(c = 0; c < dirscount; c++) {
            printf("Found  %s filename,the extension is %s.n", target, getfilextension(namelist[c]->d_name));
            free(namelist[c]);
      }
      free(namelist);
   } else {
      printf("No files found on %sn", path);
   }

}

和主代码:

int main(int argc, char * argv[])
{
   foo(".", "a"); /* The .(dot) scan the current path */
}

对于包含此文件的目录:

a.c  a.c~  a.out
a.o  makefile test.cs

输出为:

Found  a filename,the extension is .c.
Found  a filename,the extension is .c~.
Found  a filename,the extension is .o.
Found  a filename,the extension is .out.

注意:scandir()函数是 GNU 扩展/GNU 库的一部分,如果你的编译器上没有这个函数,告诉我我会为它写一个别名或使用此实现(不要忘记阅读许可证)。

如果您使用的是Windows,请使用PathFindExtension。

在 c++ 中没有列出目录内容的标准功能。因此,如果您知道应用中允许的扩展,则可以循环访问并查找文件是否存在。

其他选项是使用特定于操作系统的 API 或使用类似 Boost 的东西。您也可以使用"ls |grep *文件名"或"dir"命令转储并解析输出。