The below program works fine for a input file that has only one line. but goes to an infinite loop for a multiline file. Kindly suggest.

#include<iostream.h>
#include<conio.h>
#include<fstream.h>

void main()
{
   char data[10000];

   int i=0;

   ifstream ofile("c:\\temp\\welcome.txt");
   cout<<"File opened\n";

  // clrscr();
   
   ofile.seekg(-1,ios::end);

   while(1)

   {

    if(ofile.tellg()==-1)
    
break;
  
    i++;
    ofile.get(data[i]);


    ofile.seekg(-2,ios::cur);



  }


  data[i]='\0';

  cout<<data;


getch();

}//main

Dani AI

Generated

The infinite loop came from mixing textual newline translation with byte-oriented seeking. correctly hinted at the root cause: on Windows a text-mode stream translates "\r\n" to '\n' when reading, so stepping back two bytes after reading one character can land you in the same logical place and never reach stream start. Also, comparing tellg() to -1 is brittle — check the stream state or use streampos/eof() instead.

Two practical options:

  • For small-to-moderate files, read the whole file in binary and write bytes in reverse. Opening with ios::binary disables CRLF translation so seekg/tellg and raw byte operations are predictable. Example (simple, safe):
#include <fstream>
#include <vector>
#include <iostream>
#include <iterator>

std::ifstream in("c:\\temp\\welcome.txt", std::ios::binary);
std::vector<char> buf((std::istreambuf_iterator<char>(in)),
                      std::istreambuf_iterator<char>());
for (auto it = buf.rbegin(); it != buf.rend(); ++it)
  std::cout << *it;
  • For very large files, use a block-reverse algorithm: seek to end, repeatedly seek back by a block size (e.g. 8KB), read that block, output its bytes reversed, and continue until the start. Handle the final partial block carefully. That avoids loading the whole file into memory.

Cautions and refinements: reversing raw bytes is different from reversing user-visible characters. If the file is UTF-8 or contains multibyte encodings, reversing bytes will corrupt code points — decode to Unicode code points first, then reverse. If the intended output is “last line first” rather than a full bytewise reverse, read lines (as suggested) and print them in reverse order instead. Finally, prefer modern headers (<fstream>, <iostream>) and int main() for portability.

Recommended Answers

All 6 Replies

Member Avatar for Member #46692

What are you trying to do, read each line in reverse order, or take a line and read the characters from right to left or what?

Print the entire file in reverse. not line by line.

Member Avatar for Member #46692

test.txt

I am God yes I am
I know I am
dam right!
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <climits>

using namespace std;

class Foo
{
public:
  void reverse ( string t )
  {
    int s;
    s = t.length();

    for ( int i = s - 1; i >= 0; i-- )
    {
      cout << t[i];
    }
  }
};

int main()
{
  ifstream read ( "test.txt" );
  string line;

  vector <string> stuff;

  while ( getline ( read, line, '\n' ) )
  {
    stuff.push_back ( line );
  }
  read.close();

  int t;
  t = stuff.size();

  for ( int i = t - 1; i >= 0; i-- )
  {
    Foo test;
    test.reverse ( stuff[i] );
    cout << "\n";
  }
  cin.get();
}

My output

!thgir mad
ma I wonk I
ma I sey doG ma I

But I doubt that would work for you cos you're probably using turbo c 3.0 or something, in which case I would pretend you are writing a c program and use char arrays.

you can reverse using std::reverse :}
std::reverse(string.begin(), string.end());

> but goes to an infinite loop for a multiline file. Kindly suggest.
Because you only count bytes, not characters.

> ofile.seekg(-2,ios::cur);
By opening the file in text mode, you make it so "\r\n" is translated to "\n" when you read the file. So you get stuck in a "forward 2, back 2" loop.

For text files, it's best to read them line by line, then do whatever it is you need to do.

'seek'ing through text files is possible, but you can only seek to
- the beginning of the file
- the end of the file
- the result of a previous 'tell'

Thank you for all of your solutions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.