I look at your C ++ tag. So we will work with him not on a terrible mixture of C and C ++.
First and foremost, in addition to the data written to the array, you need to know their size, so that you can tell fout.write(...) how much data you want to write. Here, std::vector best for you. Actually, your function takes the form (I will save the transmission of the array to be filled as a parameter, perhaps this is some deep meaning):
#include <vector> void OutputResult1(std::vector<char> &Result) { Result.clear(); // вообще цикл с занулением можно было заменить одним memset. Result.reserve(1000); // только резервируем память, Result.size() вернёт ноль. size_t l = 0; for ( size_t i = 0; i < MyText.size(); ++i) { // Оставлю на вашей совести проверку выхода за пределы границ в W и bits while (MyText[i] != W[l]) { l++; } if ( MyText[i] == W[l]) { Result.push_back(bits[l]); l = 0; } } }
Well, the call and recording are made simple:
// Обратите внимание, указателей тут не используем, используем передачу по ссылке std::vector<char> BinaryCode; OutputResult1(BinaryCode); ofstream fout("C:\\Okay.dat", ios::binary); // для верности проверим if (fout) { // и запишем fout.write(BinaryCode.data(), BinaryCode.size()); }
The option above simply writes successively from 0 and 1 to the file and you can read it as is. But according to your comments, you want to pack them up to 1 bit. Well ... There are exactly two options here:
- Leave the calling code as it is and
OutputResult1 remake OutputResult1 that it immediately, during the play, "encodes" the data - Leave the
OutputResult1 function as is and change the record to the file.
Consider both options.
Option 1: change OutputResult1
#include <vector> #include <bitset> // std::bitset void OutputResult1(std::vector<char> &Result) { Result.clear(); // вообще цикл с занулением можно было заменить одним memset. Result.reserve(1000); // только резервируем память, Result.size() вернёт ноль. // пакуем в один байт std::bitset<8> outbits; size_t curbit = 0; size_t l = 0; for ( size_t i = 0; i < MyText.size(); ++i) { // Оставлю на вашей совести проверку выхода за пределы границ в W и bits while (MyText[i] != W[l]) { l++; } if ( MyText[i] == W[l]) { // я не знаю, что хранится в bits, предполагаю '1' и '0' outbits.set(curbit++, bits[l] == '1'); // Как только текущий бит дойдёт до 8 - запишем в Result if (curbit == outbits.size()) { Result.push_back(static_cast<char>(outbits.to_ulong())); curbit = 0; outbits.reset(); } l = 0; } } // тут нужно проверить, что curbit 0, иначе скинуть "недописанный" байт в Result if (curbit) { Result.push_back(static_cast<char>(outbits.to_ulong())); } }
Option 2: change the calling code
Actually it is done similarly.
// Обратите внимание, указателей тут не используем, используем передачу по ссылке std::vector<char> BinaryCode; OutputResult1(BinaryCode); ofstream fout("C:\\Okay.dat", ios::binary); // для верности проверим if (fout) { // и запишем... но не сразу. std::vector<char> bitvec; bitvec.reserve(BinaryCode.size() / 8 + 1); // +1 на всякий случай, если у нас некратное 8 число "бит" std::bitset<8> outbits; for (size_t i = 0; i < BinaryCode.size(); ++i) { size_t bit = i % 8; // остаток от деления на 8 всегда будет от 0 до 7 outbits.set(bit, BinaryCode[i] == '1'); if (bit == outbits.size() - 1) { bitvec.push_back(static_cast<char>(outbits.to_ulong())); outbits.reset(); } } // размер некратен 8, значит есть недозаполненый байт, сохраним его if (BinaryCode.size() % 8) { bitvec.push_back(static_cast<char>(outbits.to_ulong())); outbits.reset(); } fout.write(bitvec.data(), bitvec.size()); }
Conclusion
The code above was written as a demonstration of the idea, from memory and did not test for compilability and performance - I place these procedures on the shoulders of the topic starter.