2013-08-22 70 views
1

作为一个加密项目的一部分,我为了获得乐趣,我想将文件的内容(PDF,DOCX,JPEG,任何ASCII文件)与内容字符数字化,然后在最后颠倒过程以给出原始文件类型的文件,其可以像常规那样打开等。C++正确复制文件的内容

首先,我测试的时候以为我会将一个.docx文件的内容读入一个字符串,然后直接写入另一个.docx文件,名称不同。但是,完成此操作后,Microsoft Word拒绝打开该文件:“该文件已损坏,无法打开”。

这里是我用来复制文件的代码:

#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. 
} 

这是什么问题以及如何程序进行编辑,以提供有效的文件?

提前欢呼。

回答

2

您的输出流不是二进制模式。

+0

呃,谢谢,它现在有效。 – user1546083

2

看起来你忘了为输出文件(ios :: binary)设置二进制标志。