-2

I am having a text file containing 65536 integers. I am writing a C++ program given at below to read this file. But it is not working properly. It is working well for text file with few integers. But not working properly for large file.

#include(iostream)

#include(fstream)

using namespace std;

int main() {

 ifstream myReadFile;

 myReadFile.open("FileName.txt");

 char output[1000];

 if (myReadFile.is_open()) {

 while (!myReadFile.eof()) {


    myReadFile >> output;

    cout<<output;


 }

}
myReadFile.close();

system("pause");

return 0;

}

Please suggest the Solution.

Anton Gogolev
  • 107,051
  • 37
  • 191
  • 278
Shiru
  • 1
  • 1
  • 1
    Why did you tag this C when it is clearly C++? Please don't add spurious language tags. – David Heffernan Dec 26 '15 at 10:44
  • Does that code compile? Is that the actual code? – Galik Dec 26 '15 at 10:47
  • Compile with all warnings & debug info, then use the debugger. And 65536 lines is a *small* file today (a *large* file would have dozens of gigabytes) – Basile Starynkevitch Dec 26 '15 at 10:47
  • 2
    Why not read one integer at a time ? Just declare your output as an integer. – Da Mike Dec 26 '15 at 10:49
  • 3
    Do **not** use formatted input in a `char` array without setting the stream's `width()`! It results in a potential buffer overrun. **Always** set the `width()` before using `stream >> array`, e.g., using `myReadFile >> std::setw(sizeof(output)) >> output`. – Dietmar Kühl Dec 26 '15 at 11:12
  • **Always** check your input _after_ reading and do **not** try to use `eof()` to determine if input was successful (it gets set at the wrong times). Instead, use something like `while (stream >> std::setw(sizeof(buffer) >> buffer) { ... }`. I would burn and book teaching use of `eof()` in the way you did as it is clearly written by some incapable of reasoning about code to start with (if it were an actual teacher, well, the solution isn't as simple...). – Dietmar Kühl Dec 26 '15 at 11:16

1 Answers1

1

read a line each time

if (myReadFile.is_open()) {
    char output[1000];

    while (!myReadFile.eof()) {
        // just read one line
        myReadFile.getline(output, 1000);
        cout<<output;
    }
    myReadFile.close();
}
KunMing Xie
  • 1,413
  • 11
  • 14