I wrote a program 2 determine the type of file. Output i am expecting FF D8 FF E0 but i am getting 0x22fda8

#include <fstream>
#include<iostream>
using namespace std;
int main()
{
char buffer[100];
ifstream inFile;
ifstream inFile ("images.jpg", ios::in | ios::binary);
inFile.read (buffer, 20);

for (int i =0; i <20;i++)
{
char *c;
c = (char*)&buffer[i];

cout << &x << buffer[i]<<endl;
}
system("pause");
return 0;
}
You might at least provide code that compiles.
**Cire i am sorry about that, i made some modification and now i can output FFFFFFFF FFFFFFD8 FFFFFFFF FFFFFFE0. but, i want FF D8 FF F0. Thanks for the help


#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main()
{
char block[100]; //character array
ifstream file ("img.jpg", ios::in | ios::binary);
file.read (block, 20);

if (file.is_open())
{
for (int i = 0; i < 20; i++)
{
cout << hex << uppercase << (int)block[i] << " ";

}

cout << endl;
file.close();
}
else
cout << "File could not be opened " << endl;
cout << "The program read " << file.gcount() << " bytes from the
binary file "<< endl;
file.close();

return 0;
}
http://www.cplusplus.com/articles/jEywvCM9/

You are using signed variables. The bit pattern that makes up 0xFF is a negative number in a signed char. The sign bit is preserved when you cast the char to int. This is the root of your problems.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    const unsigned blockSize = 20;
    unsigned char block[blockSize]; //character array
    ifstream file("img.jpg", ios::in | ios::binary);

    if (file.read(reinterpret_cast<char*>(block), blockSize))
    {
        for (unsigned i = 0; i < blockSize; i++)
            cout << hex << uppercase <<  static_cast<unsigned>(block[i]) << " ";

        cout << "\nThe program read " << file.gcount() << " bytes from the binary file\n" ;
    }
    else
        cout << "File could not be opened " << endl;

}

It is working now and in the process i learned a few things. Thanks for all the help.
Topic archived. No new replies allowed.