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!!
|