You are here:

C++/Reading Files using file name as string



I am storing the name of the text file in a string as
string fname = "abc.txt";
string l_mline;
vector<string> p_vFileIndices;

Then I am trying to read this text file into a vector as follows:

ifstream l_ifsFile(fname.c_str());

while (getline(l_ifsFile, l_mline, '\n'))
p_vFileIndices.push_back (l_mline);
cout << "Read " << p_vFileIndices.size() << " lines.\n";
for(int i =0; i < p_vFileIndices.size(); i++)

But I see that the file is not read. It says read 0 lines.
Whats the problem in the code.
I am using VC++.
And I want to pass the name of the text file as a string only, because I will be reading different text files and in my for loop(not inculded in code), the string will be differing in the text file names.


Hi Rahul, thank you for the question.

A quick glance at your code doesn't yield any obvious errors. Can you please post the contents of abc.txt please?

One thing you might want to check though is to ensure it actually opens the file properly. You could be reading in 0 bytes because ifstream failed to open the file correctly.

Try adding this:

ifstream l_ifsFile(fname.c_str());

std::cout << "Failed to open the file: " << fname;

while (getline(l_ifsFile, l_mline, '\n'))
p_vFileIndices.push_back (l_mline);

If that gives you an error message, then you know this is a file opening issue.

Please let me know how this works for you.

- Eddie


All Answers

Answers by Expert:

Ask Experts




I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by I also know a good deal about graphics via OpenGL, and GUIs.


I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 All rights reserved.