2017-01-06 19 views
0

我试图转换为Linux/MacOS编写的C + + 14应用程序。它使用boost :: filesystem,但不用于某些iostream操作。例如:iostream GCC错误,转换为Windows :: boost :: filesystem :: iostream

boost::filesystem::path file = name; 

std::ifstream fin(file.c_str()); 

此代码是无法编译在Windows上使用MinGW的10 GCC 6.3以下:

error: no matching function for call to 'std::basic_ifstream::basic_ifstream(const value_type*)' std::ifstream fin(file.c_str());

我想如果我可以转换的std :: ifstream的提振::文件系统:: ifstream的我能得到它的工作...所以我改变了代码,以这样的:

boost::filesystem::path file = name; 

boost::filesystem::ifstream fin(file.c_str()); 
if (!fin) 
{ 
    file = pathToAppData/"files/expansion/assets/resources/basestation/config/mapFiles/racing"/name; 

    fin = boost::filesystem::ifstream(file.c_str()); 
    if (!fin) 
     throw std::runtime_error(std::string("Cannot open Anki Overdrive map file ") + file.string() + "."); 
} 

fin >> (*this); 

导致这种错误:

error: 'const boost::filesystem::basic_ifstream& boost::filesystem::basic_ifstream::operator=(const boost::filesystem::basic_ifstream&) [with charT = char; traits = std::char_traits]' is private within this context
fin = boost::filesystem::ifstream(file.c_str());

它看起来像我不能重新分配boost :: filesystem :: ifstream一旦创建......我能够将该行更改为以下,并编译,但我想知道如果它是正确的方法做到这一点:

boost::filesystem::ifstream fin(file.c_str()); 

奖金的问题:如果在Linux上此代码的工作,以及一旦我得到它的工作?

+0

什么是'name'?你可以把它传递给'ifstream'构造函数吗? –

回答

2

在Windows上boost::filesystem::path::value_typewchar_t,因为Windows路径使用16位UTF-16字符的字符串。根据C++标准,std::ifstream类只有一个构造函数,它使用窄字符串。 Visual Studio标准库为ifstream添加了额外的构造函数,这些构造函数需要很宽的字符串,但MinGW使用的GCC标准库没有这些额外的构造函数。这意味着file.c_str()返回的const wchar_t*std::ifstream的构造函数参数的错误类型。

您可以将path转换为窄字符串(通过调用file.string()),并传递到ifstream构造,虽然我不知道这是否正常工作:正如你所说

boost::filesystem::path file = name; 
std::ifstream fin(file.string()); 

boost::filesystem::ifstream不可分配(在C++ 11流不可移动或可分配之前,并且看起来Boost.Filesystem流尚未更新)。你可以简单地改变你的代码中使用,而不是试图以同样的流对象,重新打开一个新的文件重新分配给它:

fin.close(); 
fin.open(file); 

(请注意,您不需要调用c_str()因为boost::filesystem::ifstream构造TAKS一个path的说法,无论如何,不​​是一个指向字符串的指针。通过调用c_str()你刚才转换path为字符串,然后它被改回另一个path,浪费时间和内存。)

Bonus question: Should this code work on linux as well once I get it working?

是。在GNU/Linux上filesystem::path::value_typechar,所以原始代码无论如何都可以正常工作。修改后的代码也可以在GNU/Linux上运行。