I have written a code to read from a array of file in c which is something like below and it works fine.
I am trying to replicate it in C++ and use ifstream for array of files and trying to read one line from a file a time like I am doing in C. However with ifstream I am unable to move ahead.
I have ifstream files[] pointer from a function which would point me to first file
Below Code reads one line from each file at a time and keeps looping
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)
{
/* --- Code in C++ where I get stuck with ifstream and getline */ it errors out with getline saying too few arguments
#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;
}