black unicorn
black unicorn

Reputation: 11

How to read filenames in a text file in C++

I know you can use fstream to read a textfile. However if my textfile has a list of names of other files, How do I open and read those? textfile example

#include <iostream>
#include <fstream>
using namespace std;

int main(){
string line;
fstream myfile("mytextfile.txt");

 if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;

}

This just opens the stated file. How do I open and read "citylocation.txt" and "cloudcover.txt".

Upvotes: 0

Views: 918

Answers (1)

anatolyg
anatolyg

Reputation: 28241

If your file mytextfile.txt contains two names of other files

file1.txt
file2.txt

Use the following code:

int main()
{
    string filename1;
    string filename2;
    ifstream myfile("mytextfile.txt");
    getline(myfile, filename1);
    getline(myfile, filename2);

    string line;
    ifstream file1(filename1);
    ifstream file2(filename2);
    while (getline(file1, line)) // read and print first file
        cout << line << '\n';
    while (getline(file2, line)) // read and print second file
        cout << line << '\n';

    return 0;
}

If you have several (unknown number) of file names in your txt file, use a loop (marked with "read a file name" in the code below):

int main()
{
    ifstream myfile("mytextfile.txt");
    string filename;

    while (getline(myfile, filename)) // read a file name
    {
        ifstream file(filename); // open the file
        string line;
        while (getline(file, line)) // read the file
            cout << line << '\n';
    }

    return 0;
}

If any error occurs (e.g. file is not found), it's silently ignored - I omitted error handling for brevity.

Upvotes: 1

Related Questions