I’m relatively new to programming and I’m trying to write an application that outputs the hexadecimal representation of a file into a text file, then writes the bytes into a vector of unisgned chars and basically creates a copy of the original file. The problem I’m running into is that the application ends up outputting an empty file. Otherwise, the code appears to work fine; the text file contains the hexadecimal representation of the bytes and the bytes are correctly written into the byte vector. I apologize for the crappy code in advance.
int main()
{
ifstream ifile;
ofstream ofile;
ofstream ofile2;
ifstream ifile2;
string filename;
unsigned char byte;
unsigned int hexnum = 0;
vector <unsigned char>charvec;
cout << "input file name" << endl << endl;
cin >> filename;
ifile.open(filename, ios::binary);
ofile.open("OUT" + filename + ".txt");
if (ifile)
{
while (ifile >> byte)
{
ofile << "0x" << hex << static_cast<int>(byte) << ' ';
}
}
else
{
cout << "file not open";
}
ifile.close();
ofile.close();
ifile2.open("OUT" + filename + ".txt");
ofile2.open("OUT" + filename, ios::binary | ios::out);
if (ifile2)
{
while (ifile2 >> hex >> hexnum)
{
charvec.push_back(hexnum);
}
}
else
{
cout << "file not open";
}
// checking the contents of the byte vector
for (char i : charvec)
{
cout << i << ' ';
}
copy(charvec.cbegin(), charvec.cend(), ostream_iterator<unsigned char>(ofile2));
Sleep(10000000);
}
Shader is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3