For example, i open ifstream, and i want it to read not from current position to end, like always, but in reverse direction (from current position to start)?
Asked
Active
Viewed 752 times
1
-
3Might be an XY problem; if you want the data backwards then read it forwards and read the resulting data backwards. – OMGtechy Feb 14 '15 at 19:11
-
2I'd like to know the reason for _that_ :D – Ray Feb 14 '15 at 19:11
-
Seek to the end, then seek backwards X bytes, where X is the number of bytes you want to read. Then seek X + Y bytes backwards, where Y is the number of bytes you want to read next, etc. – Some programmer dude Feb 14 '15 at 19:14
-
Usually, operating systems do not support it. You have to determine the size of the file, seek to the end - one page, read a page, process and repeat. (Here, you can determine the page size) – erenon Feb 14 '15 at 19:14
-
`std::ifstream file("input.txt"); std::vector
contents { std::istreambuf_iterator – Nawaz Feb 14 '15 at 19:19{file}, std::istreambuf_iterator {} };` .. and then iterate `contents` using `rbegin()` and `rend()`. Well this should work great for smaller files. -
@Mats Not a duplicate. This OP says nothing about line-by-line. Please be more careful with your dupe hammer. – Lightness Races in Orbit Feb 14 '15 at 19:35
-
Sorry, missed that it said line-by-line in that one too (I saw it in the title of another one similar to it). I can't believe this isn't a dupe tho'. – Mats Petersson Feb 14 '15 at 19:38
2 Answers
0
You can use random file operations in C++ for this.
For ifstream ss
, you can write the command ss.seekg(0, ios::end)
to move your pointer in the text file to the end of the text file. Now you can move x
number of bytes from your current location using the ss.seekg(-x, ios::current)
current, and then read the data from that location in the forward direction. This is however a messy solution as you would need to know how many bits to move backward, or have to calculate that repeatedly. Refer to http://www.learncpp.com/cpp-tutorial/137-random-file-io/ for more information on Random file operations in C++.

therainmaker
- 4,253
- 1
- 22
- 41
0
if you want to read single characters, you can to something like this:
is.seekg(0,is.end);
while(is.tellg()>1)
{
is.seekg(-2,ios::cur);
char ch;
is.read(&ch,1);
cout<<ch<<" ";
}

mchouhan_google
- 1,775
- 1
- 20
- 28