Programming

(C++) Print Hex

steloflute 2012. 6. 6. 11:00

#include "stdafx.h"

#include <string>

#include <iostream>

#include <fstream>

#include <iomanip>


using namespace std;


int printHex(wstring fileName) {

wcout << fileName << endl;

ifstream ifs;

ifs.open(fileName, ios::binary);

if (ifs.is_open()) {

cout << "File opened." << endl;

} else {

cout << "File can't be opened." << endl;

return 1;

}

long beginPos = 0;

ifs.seekg (0, ios::end);

streamoff endPos = ifs.tellg();

streamoff fileSize = endPos - beginPos;

cout << "size is: " << fileSize << " bytes.\n";


char *memblock = new char[(unsigned int) fileSize];

        ifs.seekg (0, ios::beg);

        ifs.read (memblock, fileSize);

ifs.close();

int i;

for (i = 0; i < fileSize; i++) {

char c = memblock[i];

cout << setw(4) << hex << (int)(0xff & c);

}

return 0;

}


int _tmain(int argc, _TCHAR* argv[])

{

wstring fileName = argv[argc <= 1 ? 0 : 1];

return printHex(fileName);

}