我写了一个代码,从c中的文件数组中读取内容,如下所示,它工作正常。

我试图在C++中复制它,并将ifstream用于文件数组,并尝试一次从文件中读取一行,就像我在C中所做的那样。但是对于ifstream,我无法继续前进。

我有一个函数的ifstream files []指针,它将指向我的第一个文件

下面的代码一次从每个文件读取一行并保持循环

   char *filename[] = {"mFile1.txt", "mFile2.txt", "mFile3.txt", "mFile4.txt"};
    char line[1000];
    FILE *fp[count];
    unsigned int loop_count;
    const int num_file = count;
    char **temp = filename;
    FILE *ffinal = fopen("scores.txt", "ab+");

    for (loop_count = 0; loop_count < count; loop_count++)
    {
        if ((fp[loop_count] = fopen(*temp,"r")) != NULL)
        {
           // printf("%s openend successfully \n",*temp);
        }
        else
        {
            printf("error file cannot be opened \n");
            exit(1);
        }
        temp++;
    }

    do
    {
        for (loop_count = 0; loop_count < num_file; loop_count++)
        {
            memset(line, 0, sizeof(line));
            if (fgets(line, sizeof(line), fp[loop_count]) != NULL)
            {

/ * ---用C++编写的代码,其中卡住了ifstream和getline * // getline错误,说参数太少
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <new>
#include <sstream>
#include <string>

using namespace std;

ifstream *OpenFiles(char * const fileNames[], size_t count);

int main (void)
{
    char line[1000];
    char * const fileNames[] = {"abc.txt", "def.txt", "ghi.txt"};
    ifstream *pifstream = OpenFiles(fileNames, 3);

    for (int i = 0; i < 3; i++)
    {
        getline(pifstream[i], line);
    }

    return 0;
}

ifstream *OpenFiles(char * const fileNames[], size_t count)
{
    ifstream *pifstream = new (nothrow) ifstream[count];
    ifstream *preturn;
    preturn = pifstream;
    if (pifstream == NULL)
    {
        cerr << "error opening the file";
    }


    for (int elem = 0; elem < count; elem++)
    {
        pifstream[elem].open(fileNames[elem]);
        if (!pifstream)
        {
            cerr << "existing with error ";
            exit(1);
        }
    }

    return preturn;
}

最佳答案

#include <array>        // Constant size container
#include <vector>       // Dynamic size container
#include <fstream>      // File I/O
#include <stdexcept>    // Stock exceptions
#include <iostream>     // Standard I/O streams

// Program entry
int main(){
    // Like C array, but with useful member functions
    const std::array<const char*, 3> filenames{"test1.txt", "test2.txt", "test3.txt"};
    // Still empty vector of input file streams
    std::vector<std::ifstream> files;
    // Iterate through filenames, one-by-one
    for(auto filename : filenames){
        // Create input file stream in-place at end of vector
        files.emplace_back(filename);
        // Last input file stream in vector (see line above) is with error (opening failed)
        if(!files.back())
            // Throw error upwards (there's no catch, so the host, like the console, reports the exception message)
            throw std::runtime_error("Couldn't open file: " + std::string(filename));
    }
    // Line buffer
    std::string line;
    // Just loop 3 times (for lines)
    for(unsigned line_i = 0; line_i < 3; ++line_i)
        // Iterate through file streams
        for(auto& file : files)
            // Get current line from file stream (moves file pointer behind line + separator) and check stream status (if stream is EOF, the condition goes 'false' and nothing further happens)
            if(std::getline(file, line))
                // Write line number, character ':' and gotten line to standard output
                std::cout << line_i << ':' << line << std::endl;
    // Program exit status (usually 0 == OK)
    return 0;
}

安全,快速,简单。
这段代码需要C++ 11(现在这不再是问题了),并且没有任何其他依赖关系,仅是STL。

关于c++ - 使用ifstream代替FILE,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32238514/

10-13 09:48