代码之家  ›  专栏  ›  技术社区  ›  Crystal

用于打开文件的压缩指针表示法

  •  0
  • Crystal  · 技术社区  · 15 年前

    我正在编写一个程序来打开命令行中给出的多个文件。我首先用数组表示法。这似乎管用。现在我试着使用紧凑的指针表示法来练习和习惯指针,但是我做得不对。有人想告诉我我做错了什么吗?谢谢。

    #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;
    }
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   R Samuel Klatchko    15 年前

    end 未初始化,因此 start < end 是真是假取决于堆栈上的随机数据。您应该以以下方式初始化结束:

    end = fileObj + count;
    
        2
  •  0
  •   Miroslav BajtoÅ¡    15 年前

    必须取消对指针的引用,或者使用箭头而不是点。此外,还必须选择要打开的文件名:

    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;