简体   繁体   English

C ++完全复制文件的内容

[英]C++ Exactly copying the contents of a file

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. 作为我正在制作的加密项目的一部分,我想获取文件的内容,无论是PDF,DOCX,JPEG,任何ASCII文件,以数字方式使用字符,然后在最后反转该过程提供原始文件类型的文件,可以正常打开等。

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. 首先,当我测试时,我认为我会将.docx文件的内容读入字符串,然后将其直接写入另一个具有不同名称的.docx文件。 However, when this is done, Microsoft Word refuses to open the file: "The file is corrupted and cannot be opened". 但是,完成此操作后,Microsoft Word将拒绝打开该文件:“文件已损坏,无法打开”。

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)设置二进制标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM