0

I use this code to read a file and print it out to console:

//includes

int main(){
    std::ifstream myReadFile;
    myReadFile.open("C:\\Users\\Me\\Desktop\\Win32w\\gdip.ahk");
    char output[100];
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {


            myReadFile >> output;
            std::cout << output;


        }
    }
    myReadFile.close();
}

but after printing out all the contents of the file I get the following error:

Unhandled exception at 0x51F0742A (msvcp120d.dll) in fourteen.exe: 0xC0000005: Access violation reading location 0x002C10AB.

When I run a smaller file(script.ahk) with 5 lines it runs OK. The file gdip.ahk has bout 3300 lines.

alvitawa
  • 320
  • 2
  • 12
  • 2
    Is it your belief that `>>` is able to look at the char* it receives, and know that it points to a block of memory that is 100 characters long, so as not to exceed it? What did you think it would do if a line exceeded it? And what inspired you to use a char array instead of a `std::string`? – HostileFork says dont trust SE Oct 01 '14 at 13:39
  • 2
    And who told you to use `eof`? You should not use `eof`. If anyone tells you to use `eof`, don't listen. You should use `while (myReadFile >> output)`. – molbdnilo Oct 01 '14 at 14:04
  • I am fairly new to c++, I just got this code from a page. Thanks for the tips. – alvitawa Oct 02 '14 at 09:30

1 Answers1

1

The EOF flag is set after a read tries to read past the end of the file. See here How does ifstream's eof() work?

Community
  • 1
  • 1
Kostya
  • 1,466
  • 1
  • 9
  • 15