2010-03-04 13 views
0

我正在編寫一個程序來打開命令行中給出的多個文件。我首先用數組符號來完成它。這似乎工作。現在我正在嘗試使用緊湊的指針表示法來練習和習慣指針,但是我沒有做到正確。任何人都想告訴我我做錯了什麼?謝謝。用於打開文件的小型指針表示法

#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()) { 
//   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; 
} 

回答

1

end未初始化start < end所以不管是真/假達到什麼樣的隨機數據被留在堆棧中。您應該初始化爲:

end = fileObj + count; 
0

您必須取消引用您的指針,或使用箭頭而不是點。此外,你必須選擇你想打開的文件名:

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; 

在我看來,在這種情況下最好使用數組符號。

相關問題