1

I'm trying to read a file(a ROM actually). The thing is that my program stops before actually reaching the end of the file. Here's what I wrote:

int main(){
cout << "Entter the file to read in HEX: " ;
string fileName;
cin >> fileName;

ifstream streamLecture(fileName);
unsigned char charLu;
while(!streamLecture.eof()){
    streamLecture >> charLu;        
    cout<< hex << setw(2) << setfill('0') << short(charLu) << ' ';
}
streamLecture.close();

cout << endl;
}

This program cout a few lines of HEX values but I know there are a lot more since I read the file in a HEX editor program.

EDIT: Ok, so i'm assuming there is an EOF in the middle of my file, how do I skip it or continue reading afterwards? Thanks again

user2888798
  • 628
  • 1
  • 6
  • 13
  • Try using `while (streamLecture.get(charLu)) { //...` instead of `>>`. – jxh Oct 17 '13 at 03:20
  • @ZacHowland The problem is not the loop but why it's stopping before the end. I've tried with while(streamLecture >> charLu) but it's still stopping and I have no idea why. Thanks – user2888798 Oct 17 '13 at 03:38
  • @jxh Same problem as before, stops reading before the end – user2888798 Oct 17 '13 at 03:44
  • @user2888798 The only way your loop will break is after the `eof` bit is set, which won't happen until after you have read the actual EOF. That is, it will read more than it should, not less ... unless you have an EOF in the middle of your file. – Zac Howland Oct 17 '13 at 03:47
  • @ZacHowland Ok, so i'm assuming there is an EOF in the middle of my file, how do I skip it or continue reading afterwards? – user2888798 Oct 17 '13 at 03:49
  • @user2888798 You don't (well, shouldn't). That is a malformed file. That likely isn't your problem (unless you are trying to read in a binary file while still in text mode) - what is the data in your file? – Zac Howland Oct 17 '13 at 04:35

2 Answers2

3

Open your file in binary mode, and use get():

    ifstream streamLecture(fileName, std::ios::binary);
    while (streamLecture.get(charLu)) {
        cout<< hex << setw(2) << setfill('0') << short(charLu) << ' ';
    }
jxh
  • 64,506
  • 7
  • 96
  • 165
0

Use

while(streamLecture >> charLu){
    cout<< hex << setw(2) << setfill('0') << short(charLu) << ' ';
}
Gopi Krishna
  • 476
  • 2
  • 6
  • It doesn't work. Well it reads fine for a few lines but it stops. I'm guessing it's hitting some kind of eof (end of file character) and stopping before the end. Any ideas? – user2888798 Oct 17 '13 at 03:32