簡體   English   中英

C ++ fstream提示行為

[英]C++ fstream tellg behaviour

我正在Visual Studio 2012 (32位)中使用C ++應用程序。 當我使用fstream讀取文件並讀取四個字節兩次時,我從Tellg中得到了令人困惑的值。 我期待的是0、4和8。

std::fstream file;
file.open(filename, std::ios::in , std::ios::binary);
if ( !file.is_open())
{
    throw exception("Error opening file for reading");
}
int pos = file.tellg();  // pos is 0
boost::int32_t usedBlocks;
int size = sizeof (usedBlocks);
file.read(reinterpret_cast<char*>(&usedBlocks),sizeof(usedBlocks));
pos = file.tellg();      //pos is 3588
//Read reserved size
file.read(reinterpret_cast<char*>(&reservedSize),sizeof(reservedSize));
pos = file.tellg();     //pos is 3592

為什么會這樣?

我將代碼更改為使用fopen,fread和ftell,然后pos值為0、4和8。

usedBlocksboost::int32 boost::int32實際上是一個int ,而不是一個結構。 即使將它們更改為int也會得到相同的結果。

如果在調試器中查看pos的值,由於優化,它們可能是錯誤的。

嘗試將pos的值打印到標准輸出中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM