【问题标题】:istream streamsize ERROR reading linesistream 流大小错误读取行
【发布时间】:2017-03-13 15:16:26
【问题描述】:

我需要帮助来解决我的问题。
我想读取一个文本文件并使用指针对其进行处理。
为了测试,我有 3 个文件:a、b 和 c:

a.txt 包含 1 行,例如 29 RTY3050027/C BYZ23451 180 5.790 30.654
b.txt 包含 10 行
c.txt 包含 1000 行

我的代码是:

#include <fstream>
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    ifstream leggiROF("a.txt");

    leggiROF.seekg(0, ios::end);            
    long int dimensione=leggiROF.tellg();   
    cout << "File length: " << dimensione << " bytes" << endl;

    leggiROF.seekg(0, ios::beg);            
    char *pLeggiROF=nullptr;
    pLeggiROF=new char [dimensione];        
    // if RAM is available
    leggiROF.read(pLeggiROF, dimensione);

    if(leggiROF)
    {
        cout << "all characters read successfully.\n";
        cout << pLeggiROF << endl;
    }
    else
        /* ADDED LINES */
        int offSet=(dimensione-(dimensione-leggiROF.gcount()));
        cout << "Error: only " << leggiROF.gcount() << " bytes can be read!" << endl;
        leggiROF.read(pLeggiROF, offSet);
        cout << pLeggiROF << endl;

    leggiROF.close();

    delete[] pLeggiROF;
    pLeggiROF=nullptr;

    return 0;
}

现在我得到了 3 个不同文件的这些结果:

a.txt 1 行
29 RTY3050027/C BYZ23451 180 5.790 30.654

文件长度:41 字节
成功读取所有字符。
29 RTY3050027/C BYZ23451 180 5.790 30.654

b.txt 10行
29 RTY3050027/C BYZ23451 180 5.790 30.654
....

文件长度:412 字节
错误:只能读取 403 个字节

c.txt 1000 行
29 RTY3050027/C BYZ23451 180 5.790 30.654
....

文件长度:41480 字节
错误:只能读取 40481 个字节

【问题讨论】:

标签: c++ istream


【解决方案1】:

我解决了修改 if else 循环的问题(参见代码)。我介绍了一个offSet 变量。唯一的问题是大文件的最后一行(1000行)很脏。

10 RYN123457/2 BYZ34512 270 32.907 21.221ïû┤öÅh

看到最后一个数字后面的奇怪字符 (21.221)

【讨论】:

    猜你喜欢
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 2011-05-04
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多