2016-07-24 5 views
-2

У меня есть вектор строк 2 имен папок vector <myClass> vec_fileNames;, которые я заполнял чтением из fileNames.txt, который содержит 2 строки:C++: Использование цикла для открытия файлов

Первый

Второй

ifstream inFile("c:/file names.txt"); 

if(!inFile) 
{ 
    cout << "File Not Found!\n"; 
    inFile.close(); 
} 

else 
{ 

    string line; 
    myClass class; 


    while (getline(inFile, line)) 
    { 
     class.setFileName(line); 
     vec_fileNames.push_back(class); 
    } 

Таким образом, в этот момент мой vec_fileName[0].getFileName = Первая и vec_fileName[1].getFileName = второй

Теперь я хотел открыть файлы внутри папки, кто имена в векторе в цикле, так что я сделал это:

for(int i = 0; i < vec_fileNames.size(); i++) 

    { 

     string fileName = vec_fileNames[i].getFileName(); 

     ifstream inFile("C:/Program Folder\\" + fileName + "goalFile.txt"); 

     if(!inFile) 
     { 
      cout << "File Not Found!\n"; 
      inFile.close(); 
     } 

     else 
     { 
      while (getline(inFile, line)) 
      { 
       //do something 
      } 
    } 

До сих пор все, что хорошо для файла не открыт, за исключением. Это даже то, что можно сделать в C++ или есть ошибка в том, как я открываю файл?

+5

Почему вы всегда используете 'vec_fileNames [0]'? Разве это не 'vec_fileNames [i]'? – MikeCAT

+0

Похоже, вы используете это на окнах. Не будет ли ваша строка '' C: \ Program Folder \\ "+ fileName +" goalFile.txt "' int this case? –

+0

Рассмотрите возможность использования диапазона, основанного на цикле, - это настолько читаемо и позволяет избежать ошибок, например, всегда обращаться к одному и тому же индексу '[0]', когда ему действительно нужен текущий элемент. –

ответ

0

Я создал такую ​​же структуру папок, как у вас есть:

C:\ 
    Program Folder 
     First 
      goalFile.txt 
     Second 
      goalFile.txt 

И побежал следующий простой код. Узел, что я не храню имена файлов в классе, а прямо в вектор.

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

using namespace std; // I'm no fan of this, but you obviously used it. 

void loadFileNames(vector<string>& vec_fileNames) 
{ 
    ifstream inFile("c:\\file names.txt"); 

    if(!inFile.is_open()) 
    { 
     cout << "File Not Found!\n"; 
     return; 
    // inFile.close(); -- no need to close, it is not open! 
    } 
    else 
    { 
     string line; 

     while (getline(inFile, line)) 
     { 
      cout << line << endl; 
      vec_fileNames.push_back(line); 
     } 
    } 
} 

void openFiles(vector<string>& vec_fileNames) 
{ 
    for(int i = 0; i < vec_fileNames.size(); i++) 
    { 
     string fileName = vec_fileNames[i]; 
     string path("C:\\Program Folder\\" + fileName + "\\goalFile.txt"); 

     ifstream inFile(path.c_str()); 

     if(!inFile.is_open()) 
     { 
      cout << "File" << vec_fileNames[i] << "Not Found!" << endl; 
     } 
     else 
     { 
      cout << "opened file in folder " << vec_fileNames[i] << endl << endl; 

      string line; 
      while (getline(inFile, line)) 
      { 
       cout << line << endl; 
      } 
      cout << endl; 
     } 
    } 
} 

int main(int argc, char* argv[]) 
{ 
    vector<string> fileNames; 

    loadFileNames(fileNames); 
    openFiles(fileNames); 

    return 0; 
} 

Это работает, и производит вывод:

First 
Second 
opened file in folder First 

First goal file 1 
First goal file 2 

opened file in folder Second 

Second goalfile 1 
Second goalfile 2 

Линии First goal file 1 и т.д., содержимое двух файлов.

+0

. Я получаю «отсутствие подходящей функции для вызова на« std :: basic_ifstream » :: basic_ifstream (std: : basic_string ) '' at 'ifStream inFile (" C: \\ Program Folder \\ "+ fileName +" \\ goalFile.txt ");' – ssskh12

+0

Единственное отличие от вашего кода в том, что я вставил (двойную) обратную косую черту перед '' goalFile.txt'', то есть '' \\ goalFile.txt''. Почему это не следует компилировать, если ваш исходный код компилируется? –

+0

@ ssskh12: ifstream не имеет constrctor, который принимает std :: string, AFAIK, поэтому мне интересно, как скомпилирована ваша оригинальная программа. –