我对编程相对较新,我正在尝试编写一个应用程序,将文件的十六进制表示形式输出到文本文件中,然后将字节写入未签名字符的向量中,并基本上创建原始文件的副本。我遇到的问题是应用程序最终输出一个空文件。否则,代码看起来工作正常;文本文件包含字节的十六进制表示形式,并且字节已正确写入字节向量。我提前为糟糕的代码道歉。
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);
}
像这样怎么样?
#include <iomanip>
#include <cctype>
#include <string>
void
Hex_Dump(uint8_t const * p_array,
unsigned int length,
std::ostream& dump_stream)
{
std::string char_representation;
for (unsigned int i = 0; i < length; ++i)
{
const unsigned int i_mod_16(i % 16);
if (i_mod_16 == 0u)
{
dump_stream << std::setw(4) << std::dec << std::setfill('0') << i << " ";
char_representation.clear();
}
dump_stream << " "
<< std::setw(2) << std::hex << std::setfill('0') << static_cast<unsigned int>(p_array[i]);
const char c = static_cast<char>(p_array[i]);
if (std::isprint(c))
{
char_representation += c;
}
else
{
char_representation += '.';
}
if (i_mod_16 == 7u)
{
dump_stream << " ";
char_representation += ' ';
}
if (i_mod_16 == 15)
{
dump_stream << " " << char_representation << "\n";
}
}
}
您可能想要获取 *nix“八进制转储”或“od”的源代码。