0

I am a newbie here!Although this code completed outputting most of the file, it aborted just before it ended, what went wrong? (2VI3 is a huge data file for coordinates).

Could someone recommend better ways of writing this code?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string  *array = new string[2000];
    ifstream iFile("2VI3_SA.txt");

    if (!iFile.is_open()) {
        cerr << "error: file cannot be opened" << endl;
        abort();
    }
    int x = 0;
    while (!iFile.eof()) {

        getline(iFile, array[x]);
        cout << array[x] << endl;
        x++;

    }

    iFile.close();
    cout << x << endl;
    ofstream oFile("something.txt"); 

    if (!oFile.is_open()) {
        cerr << "error: file cannot be opened" << endl;
        abort();
    }
    for (int i = 0; i < 2000; i++) {
        if (i < 818) {
            oFile << array[i] << "\n";
        }
        else if (i<1317){
            oFile << array[i].substr(0, 8) << i - 378 << array[i].substr(11, 68) << '\n';
            //renumbering all lines below the change
        }
        else {
            oFile << array[i];
        }
    }
    oFile.close();
    delete[] array;
    return 0;
}
Xijun
  • 1
  • 1

1 Answers1

1

I see at least three problems with the code:

1.

while (!iFile.eof())

This approach to reading a file is always wrong.

2.

An array of 2000 strings gets allocated. There is no explicit check for the actual number of lines read from the input files. It is stated that the file is very big. It is highly likely that there are more than 2000 lines in the file, which will result in a corrupted heap, and undefined behavior.

3.

A more comprehensive review of the code's logic reveals the fact that reading the entire file into a memory buffer is completely unnecessary in the first place! It is perfectly sufficient to read the input file one line at a time, and then write the corresponding output line or lines to the output file, and simply tracking the number of the line currently read. The entire array can be completely eliminated. It's not needed.

Community
  • 1
  • 1
Sam Varshavchik
  • 84,126
  • 5
  • 57
  • 106