2016-09-13 3 views
1

Ich schreibe eine einfache binäre Datei, die den Inhalt einer anderen Binärdatei und einen String-Namen dieser (anderen) Datei am Ende enthalten muss. Ich fand diesen Beispielcode, der QByteArray aus der Qt-Bibliothek verwendet. Meine Frage ist: Ist es möglich, das gleiche mit std C++ Funktionen zu tun?Replace QByteArray mit Std C++ Funktionen

char buf; 
QFile sourceFile("c:/input.ofp"); 
QFileInfo fileInfo(sourceFile); 
QByteArray fileByteArray; 

// Fill the QByteArray with the binary data of the file 
fileByteArray = sourceFile.readAll(); 

sourceFile.close(); 

std::ofstream fout; 
fout.open("c:/test.bin", std::ios::binary); 

// fill the output file with the binary data of the input file 
for (int i = 0; i < fileByteArray.size(); i++) { 
    buf = fileByteArray.at(i); 
    fout.write(&buf, 1); 
} 

// Fill the file name QByteArray 
QByteArray fileNameArray = fileInfo.fileName().toLatin1(); 


// fill the end of the output binary file with the input file name characters 
for (int i = 0; i < fileInfo.fileName().size();i++) { 
    buf = fileNameArray.at(i); 
    fout.write(&buf, 1); 
} 

fout.close(); 

Antwort

0

Ja, siehe fstream/ofstream. Man könnte es wie folgt tun:

std::string text = "abcde"; // your text 
std::ofstream ofstr; // stream object 
ofstr.open("Test.txt"); // open your file 
ofstr << text; // or: ofstr << "abcde"; // append text 
1

Ihre Dateien im Binär-Modus öffnen und kopiert in "one shot" über RDBUF:

std::string inputFile = "c:/input.ofp"; 
std::ifstream source(input, std::ios::binary); 
std::ofstream dest("c:/test.bin", std::ios::binary); 

dest << source.rdbuf(); 

Dann Dateinamen am Ende schreiben:

dest.write(input.c_str(), input.length()); 

Sie können mehr Wege finden here.