As part of an encryption project I am making for fun, I would like to take the contents, of a file, be it PDF, DOCX, JPEG, any ASCII file, play around with the characters numerically and then reverse the process at the end to give a file of the original file type which can be opened etc. as normal.
First, as I test I thought that I would read the contents of a .docx file into a string, and then write that straight to another .docx file with a different name. However, when this is done, Microsoft Word refuses to open the file: "The file is corrupted and cannot be opened".
Here is the code I used to copy the file:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile("C:\\Users\\MyUser\\Documents\\This is a test.docx", ios::in | ios::binary);
inputFile.seekg(0, ios::end);
int length = inputFile.tellg();
inputFile.seekg(0, ios::beg);
string fileContents;
fileContents.resize(length);
inputFile.read(&fileContents[0], length);
inputFile.close();
ofstream outputFile("C:\\Users\\MyUser\\Documents\\TestCopy.docx", ios::app);
outputFile.write(&fileContents[0], length);
outputFile.close();
cout << "Complete.";
int n;
cin >> n; //Keeps the program open so message can be read.
}
What is the problem and how can the program be edited to give a valid file?
Cheers in advance.
您的输出流不是二进制模式。
看起来您忘了为输出文件(ios :: binary)设置二进制标志。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.