0

I'm using the following code to open a file, read char by char and get the char number as hexadecimal. The problem is that the loop never ends. What is wrong with it?

Is file >> x the equivalent to x = file.get()?

ifstream file;
    file.open(argv[1], ifstream::in|ifstream::binary);
    if (file.is_open())
    {
        unsigned char x;

        file >> std::noskipws;
        while (file >> x) {

            stringstream s;
            s << std::hex << std::setw(2) << std::setfill('0')
                << (int)x;

            std::cout << s.str();
        }

        file.close();
    }
juliano.net
  • 7,982
  • 13
  • 70
  • 164
  • How are you determining that the loop never ends? It doesn't look wrong at all. Did you copy and paste that or type it from memory? Retyping has a fantastic way of getting rid of bugs for you. – molbdnilo Aug 07 '14 at 11:36
  • I've run the code for a 1mb file and it never stops printing the elements. I just copied the code from Visual Studio. – juliano.net Aug 07 '14 at 12:57
  • Actually, I have waited 2 minutes to print every byte of the file (1MB) in a new test. Should I read a block and execute the hex function in a inner loop? – juliano.net Aug 07 '14 at 13:00
  • A 1 MB file isn't a very good testcase - use a small one (just a few characters) containing a string that you recognise immediately so you know the output is correct. And you're wasting a *lot* of time building a `stringstream` for each character. Just send the output directly to `std::cout`. – molbdnilo Aug 07 '14 at 13:40
  • I'm sending the value to a stringstream for further processing, in my final code it won't be printing this value on screen, it will send it to a new file. Should I use a different data type instead of stringstream? – juliano.net Aug 07 '14 at 13:48
  • Then you could output directly to that file stream instead. `stringstream` is mostly used if you want to build a string for some other reason than to immediately write it to another stream. – molbdnilo Aug 07 '14 at 14:10
  • But should I keep looping on every byte or should I read blocks? – juliano.net Aug 07 '14 at 16:39
  • 1
    Try the simplest thing first. If that's too slow, do the complicated thing. If that doesn't work, ask again. – molbdnilo Aug 07 '14 at 16:55

0 Answers0