我将c ++代码从linux移植到windows。我目前正在使用Visual Studio 2013来移植我的代码。
我需要读取二进制文件并使用这部分c ++代码:
// Open the stream
std::ifstream is("myfile.bin");
// Determine the file length
is.seekg(0, std::ios_base::end);
std::size_t size=is.tellg();
is.seekg(0, std::ios_base::begin);
// Create a vector to store the data
int* Data = new int[size/sizeof(int)];
// Load the data
is.read((char*) &Data[0], size);
// Close the file
is.close();
在linux中,我的二进制文件大小正确为744mb。但是,在Windows中,错误地发现我的二进制文件的大小> 4GB。我该如何纠正这个问题?
答案 0 :(得分:0)
将std::ifstream is("myfile.bin");
更改为std::ifstream is("myfile.bin", std::ios::binary);
使用当前的默认打开模式,编译器选择“char”模式。在Linux中,文件中的字符是UTF8,前128个位置是1字节字符。但对于内存UTF32,每个字符使用4个字节。在Windows中,字符是“宽字符”,每个字符2个字节。
答案 1 :(得分:0)
我终于有时间实际运行这个,虽然我必须修复一些事情,比如ios_base::beg
而不是begin
(不同的函数)另外,如上所述,数组分配应该是int* Data = new int[size / sizeof(int) + 1]; // At most one extra int
我发现了你的问题:你不在正确的目录中。检查您是否成功打开了该文件。如果不这样做,那么size
就会得到一个巨大的垃圾值(可能为-1,但未签名,如此庞大)。
试试这个在Windows中找到你的目录:(可能需要Windows.h或者我刚刚“已经拥有”的东西)
char dirBuf[256];
GetCurrentDirectory(256, dirBuf);
cout << "Current directory is: " << dirBuf << endl;
查看您的文件是否在哪里并相应地移动它。或者在构造函数中指定ifstream的ENTIRE路径。
此外,它与ios::binary
无关。两种方式都可以正常工作,如果文件不存在则会失败。
答案 2 :(得分:0)
function nWin() {
var w = window.open();
var html = $(".ticker-pop-out").html(); //This class reference to the button, not to the class you want to render
$(w.document.body).html(html);
}
标准不要求std::size_t size=is.tellg();
从文件开头返回字节偏移量。一般来说,这可能不是获取文件大小的可靠方法,尽管它可能会在Linux和Windows上实现您所期望的。
tellg
方法的返回类型为tellg
,因此您从隐式转换为std::basic_stream::pos_type
开始,这可能适合也可能不适合。例如,在32位版本中,可以想象文件的大小可能大于std::size_t
可以表示的大小。
但根本问题是你没有检查错误。如果您已禁用例外,那么std::size_t
会通过返回tellg
来报告错误。当你将它转换为无符号类型(pos_type(-1)
是)时,你得到一个非常大的值。我怀疑您无法打开该文件,并且由于您没有检测到该错误,std::size_t
和seekg
都失败了。然后,您将tellg
强制转换为pos_type(-1)
,这使文件看起来很庞大。
您还遇到其他人已经注意到的问题:当文件不是std::size_t
的倍数时,无法以二进制模式打开文件并为缓冲区计算错误的大小。
获得文件大小最可靠的是使用操作系统的API。在Windows上,您可以改为:
int
答案 3 :(得分:-1)
int* Data = new int[size/sizeof(int)];
你为什么要这样做?您将尺寸除以4.您不想这样做。它应该是int* Data = new int[size]
此外,它应该是std::ifstream f("filename.bin", std::ios::binary);