Open files, passing variable as filename

3

I have the following situation, a file "tables.txt" where I have around 2000 lines with filenames which I want to pass line by line taking the name of the files and checking which ones exist and which do not.

The problem occurs when after getting the name of the file to be checked I try to pass it to open it after ifstream obj (arq) , the strange thing is that if I type by passing the string with the path and not the variable arq that is string the file is read without problems.

Follow the code used:

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


int main () {
    string line;    
    ifstream myfile ("tabelas.txt"); 
    if (myfile.is_open()){
        while (! myfile.eof() ) 
        {
            getline (myfile,line); 
            string arq = "..\dados\"+ line+".csv";

            ifstream obj (arq);
            if (!obj) 
                cerr<<"Ocorreu um erro ao abrir o arquivo"<<endl;
        }
    myfile.close();
    }

    else cout << "Unable to open file"; 

    return 0;
}

The following image demonstrates the error:

link

    
asked by anonymous 27.07.2016 / 13:36

1 answer

3

I rebuilt it to read files the way I normally do.

Follow the code below:

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

int main () {
    ifstream myfile ("x.txt", ifstream::in);
    string line;
    if(myfile.is_open()){
        while(getline(myfile, line)){
            line = "..\dados\" + line + ".csv";
            ifstream testfile (line.c_str(), ifstream::in);
            if(testfile.is_open()){
                cout << "O arquivo '"<< line <<"' existe\n";
            }else{
                cout << "O arquivo '" << line << "' nao existe\n";
            }
        }
    }
    myfile.close();


    return 0;
}
    
27.07.2016 / 15:03