C++即使 gcount 返回 0,iostream 也不设置 eof 位

发布于 2024-08-29 10:15:58 字数 812 浏览 0 评论 0原文

我正在Windows下开发一个应用程序,我正在使用fstreams来读取和写入文件。

我正在使用像这样打开的 fstream 进行写入:

fs.open(this->filename.c_str(), std::ios::in|std::ios::out|std::ios::binary);

并使用此命令进行写入,

fs.write(reinterpret_cast<char*>(&e.element), sizeof(T));

每次写入后关闭文件,并

fs.close()

使用像这样打开的 ifstream 进行读取:

is.open(filename, std::ios::in);

并使用此命令进行读取:

is.read(reinterpret_cast<char*>(&e.element), sizeof(T));

写入进展顺利。但是,我以这种方式循环读取:

while(!is.eof())
{
  is.read(reinterpret_cast<char*>(&e.element), sizeof(T));
}

即使应该到达文件末尾,程序也会继续读取。 istellg pos 为0,gcount 也等于0,但fail 位和eof 位都可以。

我对此感到疯狂,需要帮助......

I'm developping an application under windows, and i'm using fstreams to read and write to the file.

I'm writing with fstream opened like this :

fs.open(this->filename.c_str(), std::ios::in|std::ios::out|std::ios::binary);

and writing with this command

fs.write(reinterpret_cast<char*>(&e.element), sizeof(T));

closing the file after each write with

fs.close()

Reading with ifstream opened like this :

is.open(filename, std::ios::in);

and reading with this command :

is.read(reinterpret_cast<char*>(&e.element), sizeof(T));

The write is going fine. However, i read in a loop this way :

while(!is.eof())
{
  is.read(reinterpret_cast<char*>(&e.element), sizeof(T));
}

and the program keeps reading, even though the end of file should be reached. istellg pos is 0, and gcount is equal to 0 too, but the fail bit and eof bit are both ok.

I'm running crazy over this, need some help ...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

当爱已成负担 2024-09-05 10:15:58

试试这个:

while(is.read(reinterpret_cast<char*>(&e.element), sizeof(T))) {}

此外,您还应该使用 binary 标志打开 istream

is.open(filename, std::ios::in | std:ios::binary);

如果它永远读取,它会读取什么? T是什么类型?

Try this:

while(is.read(reinterpret_cast<char*>(&e.element), sizeof(T))) {}

Also you should open the istream with the binary flag as well:

is.open(filename, std::ios::in | std:ios::binary);

If it reads forever, what does it read? What type is T?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文