无法在循环C ++中打开文件

时间:2013-03-21 16:59:01

标签: c++ file loops

我有一个c ++应用程序,其代码如下:

for (int i = 0; i < ALL_EPID_CERTS_LENGTH; i++)
            {
            std::ifstream file(; 
            file.open(path.append(ALL_EPID_CERTS_1_0[i]), std::ios::in | std::ios::binary); 
            if(file.is_open()) 
            {
                // get the length of the file 
                file.seekg(0, ios::end); 
                size_t fileSize = file.tellg(); 
                file.seekg(0, ios::beg);
                // create a vector to hold all the bytes in the file
                vector<byte> data(fileSize, 0);
                // read the file
                file.read(reinterpret_cast<char*>(&data[0]), fileSize);             
                byte *tempCerts = new byte[data.size()+1];
                memset(tempCerts,0,fileSize+1);
                std::copy(data.begin(), data.begin()+(data.size()), tempCerts);
                // !!!!check if NULL and place for NULL are needed
                for (int j = 0; j < data.size(); j++)
                {
                    list.push_back(tempCerts[j]);
                }
                file.close();
            }
            }

在第一次迭代中,循环执行预期,但是从第二次循环开始 - file.is_open()返回false。 所有文件都存在。 请你解释一下我的错误???

2 个答案:

答案 0 :(得分:9)

你做path.append - 什么是path?在第一次迭代后你期望它是什么 - 将ALL_EPID_CERTS_1_0[1]附加到ALL_EPID_CERTS_1_0[0]是否正常?

答案 1 :(得分:0)

关闭流后,您可能需要调用infile.clear();清除状态位,否则无法使用相同的流打开新文件。

另外:您确定需要在每次迭代时附加到路径吗?在每次追加调用后输出路径变量,并检查路径是否正确。我希望在第二次迭代中,路径字符串看起来像这样:“c:/some/path/file1.txtfile2.txt”

在这种情况下,我会使用stringstreamsprintf来生成路径,并确保不要更改路径变量。