Convert file to hex and back
Sep 13, 2016 at 2:21am UTC
I am trying to make a program that will load any file and convert it to a vector of hex values and then turn those back into the file that was loaded, but it only is working with files that have text only in them. If I try to open an image file or any others, Windows tells me that it is unable to open them. If I open the original file and the copy in notepad++, it seems like the files are exactly the same, but the copy still will not open. What am I doing wrong here?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
using namespace std;
bool exists(string name) {
fstream file(name);
return file.good();
}
vector<char > LoadTempFile() {
vector<char > fileData;
fstream file;
string loadedFile = "" ;
cout << "Loading File..." << endl;
file.open("temp.txt" );
if (file.good()) {
while (!file.eof()) {
string temp;
getline(file, temp);
loadedFile += temp;
}
}
string data = loadedFile.substr(loadedFile.find_first_of('{' ) + 1, loadedFile.find_last_of('}' ) - loadedFile.find_first_of('{' ) - 1);
stringstream ss(data);
string token;
cout << "Converting..." << endl;
while (getline(ss, token, ',' )) {
stringstream convert(token);
int value;
convert >> hex >> value;
fileData.push_back(value);
}
return fileData;
}
int main() {
system("cls" );
string fileName;
cout << "Enter file name to convert: " ;
getline(cin, fileName);
if (!exists(fileName)) {
cout << "Can't find file" << endl;
system("pause" );
main();
}
string newFileName = "newFile" + fileName.substr(fileName.find_last_of('.' ), string::npos);
string command = "bin2h.exe file<" + fileName + ">temp.txt" ; //program used to convert to hex
system(command.c_str());
vector<char > loadedTemp = LoadTempFile();
cout << "Writing to new file..." << endl;
fstream newFile;
newFile.open(newFileName, ios::out);
std::stringstream ss;
for (unsigned i = 0; i < loadedTemp.size(); i++) {
newFile << loadedTemp[i];
}
newFile.close();
system("del temp.txt" );
}
Sep 13, 2016 at 2:50am UTC
Ok I figured out the problem.
1 2
fstream newFile;
newFile.open(newFileName, ios::out);
should be
fstream newFile(newFileName, ios::out | ios::binary);
Topic archived. No new replies allowed.