If you just want to take the binary data an present it in reverse order, regardless of it's meaning, your code is ok.
Some recommendations:
You should then open the stream in binary
for consistency accross the platform (i.e. avoid that a newline is transformed in double newline on platforms such as windows which encode it as 0x0d,0x0a
).
You could also consider using in the loop the relative position to the current one, to navigate backwards, instead of always going to the end and repoistion yourself from the absolute position from the end.
Here the fine-tuned code:
ifstream fileA("test.txt", ios::binary); // binary data because binary revert
fileA.seekg(-1, ios::end); // position on last char to be read
char ch;
for (; fileA.get(ch); fileA.seekg(-2, ios::cur)) // try to read and rewind.
std::cout << ch;
Your code is however not able to read proper UTF8 encoded files, because the multibyte sequences will be mecanically revereted, and their reverted version is invalid UTF8:
- This is not an issue if you only have ASCII caracters in your file.
- If UTF8 consistency is a problem for you, you could consider a very simple workaround: if you read a character
u
for which (u & 0xC0) == 0x80
, you have to read all the preceding chars until this condition goes false, and output the group of bytes (between 2 and 8) in the correct order.
Here how to do it:
... // If UTF-8 must be processed correctly
fileA.seekg(-1, ios::end);
char ch, buft[9]{},*p;
bool mb=false;
for (; fileA.get(ch); fileA.seekg(-2, ios::cur))
{
if (mb) { // if we are already processing a multibyte sequence
if ((ch & 0xC0) == 0x80 && p!=buft) // still another byte ?
*--p=ch;
else {
cout <<ch<<p; // if no other output the current leading char followed by the multibyte encoding that we've identified
mb=false; // and multibyte processing is then finished
}
}
else if ((ch & 0xC0) == 0x80) { // if a new multibyte sequence is identified
mb =true; // start its processing
buft[7]=ch;
p=buft+7;
}
else std::cout << ch; // normal chars ar procesed as before.
}
Here a runnable demo.
Last point: removing the last byte from the input stream is operating system dependent. You should have a look at this SO question to get answers on how to do it on linux/posix and windows.