1

I'm writing a simple binary file that must contain the contents of another binary file and a string name of this (another) file at the end. I found this sample code that uses QByteArray from the Qt library. My question is: is it possible to do the same with std c++ functions?

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();
lucke84
  • 4,516
  • 3
  • 37
  • 58

2 Answers2

1

Open your files in binary mode and copy in "one shot" via 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();

Then write filename at the end:

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

You can find more ways here.

Community
  • 1
  • 1
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
0

Yes, refer to fstream / ofstream. You could do it like this:

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
markus-nm
  • 805
  • 5
  • 8