繁体   English   中英

vc140 x64项目缺少c ++ libgen.h(mingw)-帮助器函数

[英]c++ libgen.h (mingw) missing for vc140 x64 project - helper functions

我有以下辅助功能:

std::string
pathname_directory(const std::string &pathname)
{
  char buffer[pathname.size() + 1];
  memset(buffer, 0, sizeof(buffer));
  std::copy(pathname.begin(), pathname.end(), buffer);
  return std::string(dirname(buffer));
}

std::string
pathname_sans_directory(const std::string &pathname)
{
  char buffer[pathname.size() + 1];
  memset(buffer, 0, sizeof(buffer));
  std::copy(pathname.begin(), pathname.end(), buffer);
  return std::string(basename(buffer));
}

它依赖于mingw头文件libgen.h。

1)为什么在包含“ char buffer [pathname.size()+ 1];”的行中,VS给出错误“表达式必须具有恒定值”?

2)是否有用于VS 2015的预定义函数来处理此问题?

libgen.hPosix头文件 ,因此问题与mingw没有特别关系。

编译器抱怨:

char buffer[pathname.size() + 1];

因为标准C ++(任何标准)都禁止使用可变长度数组(尽管C99允许使用它们)。

您可以通过重写函数来避免使用VLA:

#include <string>
#include <memory>
#include <algorithm>
#include <libgen.h>

std::string
pathname_directory(const std::string &pathname)
{
    char const *cs = pathname.c_str();
    std::size_t cslen = pathname.size() + 1;
    std::unique_ptr<char[]> pbuf(new char[cslen]);
    std::copy(cs,cs + cslen,pbuf.get());
    return dirname(pbuf.get());
}

std::string
pathname_sans_directory(const std::string &pathname)
{
    char const *cs = pathname.c_str();
    std::size_t cslen = pathname.size() + 1;
    std::unique_ptr<char[]> pbuf(new char[cslen]);
    std::copy(cs,cs + cslen,pbuf.get());
    return basename(pbuf.get());
}

但是,从dirnamebasename获得的帮助可能不值得像这样(或实际上是您尝试获取它的方式)那样繁琐。

特别是这样,如果您想要的pathname_directory(pathname)是所有pathname ,但不包括最后一个路径分隔符,而您想要的pathname_sans_directory(pathname)是所有pathname在最后一个路径分隔符之后。 因为dirnamebasename会通过返回“”使您感到惊讶。 如果您希望使用空字符串。 请参阅dirname和基basename文档。

如果是这样,那么最少的麻烦便是自己动手做:

#include <string>

std::string
pathname_directory(const std::string &pathname)
{
    std::size_t len = pathname.find_last_of("/\\");
    return len == std::string::npos ? "": pathname.substr(0,len);
}

std::string
pathname_sans_directory(const std::string &pathname)
{
    std::size_t len = pathname.find_last_of("/\\");
    return len == std::string::npos ? pathname : pathname.substr(len + 1);
}

或者您可以在Windows上使用LLVM(clang)进行编译。 您可以将clang作为C ++下Visual Studio安装的一部分进行安装。 Clang允许使用可变长度数组,但MSBuild(Visual Studio中的默认值)不允许。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM