Copy text to another txt file in binary

I have problems with converting text to binary. I need to convert the text in character.txt into binary and print the binary in bcharacter.txt

i've got this chunk of codes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <fstream>
#include <iostream>
using namespace std;


int main () {
  char ch;
  ifstream infile;
  ofstream outfile;
  filebuf *inbuf, *outbuf;

  infile.open ("character.txt", ios::out | ios::app | ios::binary);
  outfile.open ("bcharacter.txt");

  inbuf=infile.rdbuf();
  outbuf=outfile.rdbuf();

  ch = inbuf->sgetc();
  while ( ch != EOF)
  {
    outbuf->sputc (ch);
    ch= inbuf->snextc();
  }

  outfile.close();
  infile.close();

  cout << "Copied from character.txt to bcharacter.txt!" << endl << endl;

  return 0;
}


this code does not work. It only copy the exact text from character.txt to bcharacter.txt without converting it to binary eventhough i added this code -- infile.open ("character.txt", ios::out | ios::app | ios::binary);

So, how can i change my codes in order for it to convert text to binary before printing it to a new text file? I'm not sure if my codes are correct..
Last edited on
Now, by binary, do you mean ones and zeroes? despite the name, the ios::binary flag does not actually convert it into binary numbers.

I guess you could read the file into a string, and loop through every character, replacing it with its binary value counterpart... As far as I know, there's no existing function that does such a thing, but it should be quite feasible to write one yourself.
Topic archived. No new replies allowed.