C++ Program to Print the Contents of File in Reverse Order

This C++ Program which prints the lines of a file from bottom to top. The program creates an input file stream, reads a line on every iteration of a while loop and saves every line in a string vector. The for loop prints the lines from the end of the vector to the start of it.

Here is source code of the C++ program which prints the lines of a file from bottom to top. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Print Lines of a File from Bottom to Top
  3.  */
  4. #include <iostream>
  5. #include <fstream>
  6. #include <vector>
  7.  
  8. int main()
  9. {
  10.     std::string line;
  11.     std::vector<std::string> v;
  12.     std::ifstream file("main.cpp");
  13.  
  14.     while (getline(file, line))
  15.     {
  16.         v.push_back(line);
  17.     }
  18.     /* Printing the lines from Bottom to Top */
  19.     for (int i = v.size() - 1; i >= 0; i--)
  20.     {
  21.         std::cout << v[i] << std::endl;
  22.     }
  23.     return 0;
  24. }

$ g++ main.cpp
$ ./a.out
}
    }
        std::cout << v[i] << std::endl;
    {
    for (int i = v.size() - 1; i >= 0; i--)
    }
        v.push_back(line);
    {
    while (getline(file, line))
 
    std::ifstream file("main.cpp");
    std::vector<std::string> v;
    std::string line;
    int count = 0;
{
int main()
#include <vector>
#include <fstream>
#include <iostream>
 */
 * C++ Program to Print Lines of a File from Bottom to Top
/*

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.