MinGW的tellg()问题

来源:互联网 发布:java开源文档管理系统 编辑:程序博客网 时间:2024/06/10 02:55
MinGW的tellg()问题

问题的原始描述见:
mingw3.4.2 下似乎 fellg 有bug


写了段代码,显示出tellg()似乎有问题:
#include <iostream>
#include 
<fstream>
using namespace std;

int main()
{
    fstream f(
"a.txt",ios::out|ios::in|ios::trunc);
    f 
<< "abcdefg/n "// f << "abcdefg"; 就是多了个/n,所以来问题了
    f.seekg(0);

    
char ch;
    cout 
<< "tellg=" << f.tellg() << endl;
    f 
>> ch;
    cout 
<< ch << endl;
    cout 
<< "tellg=" << f.tellg() << endl;
    f 
>> ch;
    cout 
<< ch << endl;
    cout 
<< "tellg=" << f.tellg() << endl;

    system(
"pause");
    
return EXIT_SUCCESS;
}


输出为

tellg=0
a
tellg=2
c
tellg=4

而不是

tellg=0
a
tellg=1
b
tellg=2

结果显示tellg()使读指针前移了一位,造成数据丢失。

查看源代码,应该是以下调用的结果。
pubseekoff(0, ios_base::cur, ios_base::in);

搜索tellg bug, 找到了确切的解释:
http://www.mingw.org/MinGWiki/index.php/Known%20Problems

因为tellg()调用seek()来获取当前指针,MinGW调用的MSVCRT库对于在文本文件中的任意位置seek()是未定义的,仅支持文件头或尾的seek().

Cygwin平台上也有该Bug报告:
http://www.cygwin.com/ml/cygwin/2006-06/msg00232.html

而使用STLPort则没有问题,因为STLPort没有调用seek()有获取位置,而是直接返回保存值。
原创粉丝点击