Compact pointer notation for opening files
I'm writing a program to open up multiple files given at the command line. I first did it with array notation. That seems to work. Now I am trying to use compact pointer notation for practice and getting used to pointers, but I am not doing it right. Anyone want to tell me what I'm doing wrong? Thanks.
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
ifstream *OpenFiles(char * const fileNames[], size_t count)
{
ifstream *fileObj = new ifstream[count];
if (fileObj == NULL) {
cerr << "Failed to create space for files";
exit(EXIT_FAILURE);
}
// working loop with array notation
// for (int loopCount = 0; loopCount < (int) count; loopCount++) {
// fileObj[loopCount].open(fileNames[loopCount], ios::out);
// if (fileObj[loopCount].is_open(开发者_StackOverflow中文版)) {
// cout << "Opened " << fileNames[loopCount] << "\n";
// }
//
// }
// start compact pointer notation that doesn't work
ifstream *start, *end;
for (start = fileObj; start < end; start++) {
start.open(fileNames, ios::out);
if (start.is_open()) {
cout << "Opened " << start << "\n";
}
}
return fileObj;
}
end
is not initialized so whether start < end
is true/false is up to what random data was left on the stack. You should initialize end with:
end = fileObj + count;
You must dereference your pointers, or use arrow instead of dot. Additionally, you have to select the filename you want to open:
ifstream *end = fileObj + count;
for (ifstream *start = fileObj; start < end; start++) {
start->open(fileNames[start-fileObj], ios::out);
if (start->is_open()) {
cout << "Opened " << fileNames[start-fileObj] << "\n";
}
}
return fileObj;
In my opinion, it is better to use the array notation in this case.
精彩评论