c++ - istream streamsize 读取行错误

标签 c++ istream

我需要帮助来解决我的问题。
我想读取一个文本文件并使用指针处理它。
我有 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 字节

最佳答案

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

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

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

关于c++ - istream streamsize 读取行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40343878/

相关文章:

C++ While( cin >> x) 是如何工作的?

c++ - qt creator可以使用环境变量吗?

c++ - Qt/C++中如何从QApplication继承样式表

c++ - 将 for_each 与 tolower() 一起使用

c++ - 当我将 int 添加到 char ('a' + 1 时调用哪个 operator+ 函数)

c++ - 访问冲突写入位置

c++ - 如何检查 std::cin 是否与终端或管道关联

c++ - 正确实现单链表C++

windows - 使用 Windows IStream 下载文件

c++ - 如何将 istream * 转换为字符串或仅打印它?