c ++:使用循环打开文件

时间:2016-07-24 15:51:46

标签: c++ file-io ifstream

我有一个包含2个文件夹名vector <myClass> vec_fileNames;的字符串向量,我通过阅读包含2行的fileNames.txt来填充:

  

第一

     

第二

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 ++完成,或者我打开文件的方式有错误吗?

1 个答案:

答案 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等是两个文件的内容。