【发布时间】: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 个字节
【问题讨论】:
-
谢谢。我正在研究其他帖子