使用Cygwin编译时出现fstream错误

Getting fstream errors when compiling with Cygwin

本文关键字:fstream 错误 Cygwin 编译 使用      更新时间:2023-10-16

我正在编写一个程序,当我尝试使用Cygwin进行编译时,遇到了一些奇怪的编译器错误。该程序使用Visual Studio C++Express编译和运行得很好,所以它似乎与Cygwin有关。所有的错误似乎都是同一类型的。下面是一个代码示例:

int count_records(void)
{
EMPL_TYPE empl_rec;
fstream empl_infile;
empl_infile.open(filepath, ios::in|ios::binary);
int count = 0;
empl_infile.read((char *) &empl_rec, sizeof(empl_rec));
while (!empl_infile.eof())
{
    count++;
    empl_infile.read((char *) &empl_rec, sizeof(empl_rec));
}
empl_infile.close();
cout << "Records Counted: " << count << endl;
return count;
}

这是与该部分相关的错误:

Assignment2.cpp:在函数int count_records()': Assignment2.cpp:34: error: no matching function for call to std::basic_stream>::open(const std::string&,std::_Ios_Openmode('/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/fstream:819:注意:候选为:void std::basic_fstream&lt_CharT,_Traits>::打开(const char*,std::_Ios_Openmode([其中_CharT=char,_Trait=std::char_Traits]

同样,在使用Visual Studio进行编译时,我不会得到这个错误,只是使用Cygwin。如果有人有任何想法,我们将不胜感激。非常感谢。

令人惊讶的是,在C++11标准问世之前,文件流的open((方法只使用C风格的字符串。用empl_infile.open(filepath.c_str(), ios::in|ios::binary);替换您的open语句(注意文件路径上的.c_str()调用(,或者在Cygwin中的编译行中添加-std=c++11。

可能您在VS上有C++11支持,而在Cygwin上没有。fstream::open方法以const char*作为C++03中的第一个参数。C++11提供了采用CCD_ 6的过载。

你可以像这个一样修复它

mpl_infile.open(filepath.c_str(), ios::in|ios::binary);