C++/Reading Files using file name as string
Expert: Eddie - 7/4/2007
QuestionHi,
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++)
cout<<p_vFileIndices[i]<<endl;
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.
Thanks,
Rahul
AnswerHi 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());
if(!l_ifsFile.is_open())
{
std::cout << "Failed to open the file: " << fname;
return;
}
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