You are here:

C++/file handling in c++


"Hi, im Carl and I am new to c++... I would just like to know if how
could I open a text file in C++?... For example, I have a file named
"file.txt", that I have save from a notepad... Then if I am going to run my
program, the user must input the path where he/she saved his/her
file...  When i a;lready have the file, for example the file opened was
"CARL", my program needs to invert it using STACT... So the output of my
program would be

I am asking for your assistance for me to be able to be a goog
programmer someday... Thanks to you, and GodBless!!!"  

Your program is not going to be short. You will have to write a stack class, which you should be able to do, if you understand dynamic allocation and stack. If you dont, then go get a data structures book, for example, Cormen's book.

As for inputting from the file, you could do the following:

#include <fstream> // if you're using .h files, you're writing C, not C++
#include <string>
#include <vector>
std::vector<char> input_characters_from_file(std::string filename) { // std is a namespace
   std::ifstream f(filename); // static (stack) allocation
   if(!f) {
       // log error
       std::cout << "Could not input file: " << filename << " for reading.";
       return 0;
   std::vector<char> v = new std::vector<char>(); // dynamic (heap) allocation
   while(f) { // same as !f.eof()
       char c;
       f >> c;
   return v;

This function returns null if file could not open, so remember to handle this case in the calling function.

You have not told me whether you have programmed before in some other language, so I will wrap up here. If you are serious about learning the language I recommend Bruce Eckel's book "Thinking in C++" which has both an online and a print version. Just search for it on google.

Get back when needed.


All Answers

Answers by Expert:

Ask Experts


Amit Kumar


I can answer Cplusplus language and library questions, including STL, ACE, Boost. I have a good background in Mathematics.


Programming in CPP for about 8 years. Industry experience of 4 years.

Bachelors and Masters in Computer Science from Indian Institute of Technology Delhi.

©2017 All rights reserved.