1

i need help to solve my problem.
I want to read a text file and work on it using pointers.
I have, for test, 3 files: a, b and c:

a.txt contains 1 line like 29 RTY3050027/C BYZ23451 180 5.790 30.654
b.txt contains 10 lines
c.txt contains 1000 lines

My code is:

#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;
}

Now i have these results with the 3 different files:

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

File length: 41 bytes
all characters read successfully.
29 RTY3050027/C BYZ23451 180 5.790 30.654

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

File length: 412 bytes
ERROR: only 403 bytes could be read

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

File length: 41480 bytes
ERROR: only 40481 bytes could be read

Massimo D. N.
  • 316
  • 1
  • 6
  • 17

1 Answers1

0

I solved modifing the if else cycle (see code). I introduced an offSet variable. The only thing is that the last line of the big file (1000 lines) is dirt.

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

see the strange characters after the last number (21.221)

Massimo D. N.
  • 316
  • 1
  • 6
  • 17