LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to read filenames from a vector and open them in C++ (https://www.linuxquestions.org/questions/programming-9/how-to-read-filenames-from-a-vector-and-open-them-in-c-664899/)

tnjones 08-23-2008 04:27 PM

How to read filenames from a vector and open them in C++
 
Hello,
I am trying to write a program in C++ that stores all of the names of textfiles in a current directory in a vector,once having the filenames I need to open each and disply all vaild e-mail addresses. At this time I have it getting all filenames and stroing them in a vector. I even have a test program that is reading files and displaying all valid addresses. However, when trying to put everything together,I am having problem with opening the files(names stored in array). I have a loop to go through the vector and read and store the filename to a variable and then use the traditonal ifstream to open the file but it isn't working.Below is just a sample program where I have strored filenames in the vector and trying to open the files.

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <fstream>

using namespace std;
int main()
{
vector<string> vec;
string filename;
string line;
ifstream myfile;
vec.push_back("example.txt"); vec.push_back("atest.txt"); vec.push_back("backup.txt");
sort(vec.begin(), vec.end());
for (int i = 0; i < vec.size(); i++)
{
// cout << vec[i] << endl;
filename = vec[i];
myfile.open("filename");

if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}

myfile.close();
}
else cout << "Unable to open file";

}

return 0;
}

With this in mind, how do you open filenames that are stored in a vector?Any help will be greatly appreciated!!

Aidin_36 08-24-2008 03:53 AM

Seems the problem is this line:

myfile.open("filename");

`filename' is the name of a variable, and you should write:

myfile.open(filename);

That should solve your problem!

NOTE: It's a good idea to use `at' function instead of those []. so change `filename = vec[i];' to `filename = vec.at(i);' But it's not neccessary.

tuxdev 08-24-2008 08:48 AM

You should also use iterators rather than an index, and declare variables as late as possible:
Code:

for (std::vector<std::string>::const_iterator end = vec.end(), iter = vec.begin();iter != end;++iter)
{
  std::ifstream file(*iter);
  for(!file.eof())
  {
      std::string line;
      std::getline(file, line);
      std::cout << line << endl;
  }
}



All times are GMT -5. The time now is 01:42 PM.