可以在不读取文件两次的情况下完成吗?C++

use*_*120 0 c++

我在main.cpp中做的是读取文本文件两次:一次从每个路径名中删除'\',然后再次将文件的原始名称提供给我的实现文件中的SetPath().

// This a read file sub-routine called in the main function.
// Its purpose was intentionally set out to read the file, and pass information
// to functions to MyClassFile Implementational file.


// global varaible to have the file spec.
char MyClass::List_[ ARRY_SZ ] = {};

int main()
{

..
inFile.open( MyClass::List_, ios::in  );

    while ( inFile.peek() != '\n' )
    {
        inFile.get( ch );
        if ( ch == 92 )
            count++;
    }

    inFile.clear();
    inFile.close();

    inFile2.open( MyClass::List_, ios::in  );
    while ( inFile2.peek() != EOF )
    {
            for( unsigned short i = 0 ; i < count; i++ )
            {
                inFile2.getline( tmpArray, ENTRY_SZ, 92 );  
            }

            inFile2.getline( tmpArray, ENTRY_SZ, '\n' );
            MyObject = new MyClass( tmpArray );  // Name W/O Path   
            LinkedObject->AddLink( MyObject );
            lineCount++;
    }
    while ( inFile2.peek() != EOF )
    {
            inFile2.getline( tmpArray, ENTRY_SZ, '\n' );
            MyObject->GetPath( tmpArray ); 
    }
    inFile2.clear();
    inFile2.close();
}           
Run Code Online (Sandbox Code Playgroud)

文本文件具有以下格式:

C:/temp/fileID
C:/temp/FileID2
Run Code Online (Sandbox Code Playgroud)

我需要将名称传递给复制构造函数.我需要将仍在文本文件中的完整路径名传递给我的实现文件中的MyClass :: GetPath()函数.

有没有办法在不读取文件两次的情况下执行此操作?我希望你能看到我在这里尝试做什么.我可能只是回到开头或类似的东西

Jon*_*ler 8

重申问题:

  • 我有一个文本文件,其中每行包含一个Windows样式的绝对路径名.
  • 我需要将文件的基名传递给构造函数,并将全名传递给另一个函数.

我可以不重新读取文件吗?

答案是肯定的.

  • 将每一行读入一个字符串(因此它包含完整路径).
  • 如有必要,请删除尾随换行符.
  • 从完整路径创建一个仅包含文件基本名称的新字符串.
  • 使用basename调用构造函数.
  • 使用路径名调用另一个函数.

这是稍微多一点的字符串操作 - 它大大减少了文件操作,这就是性能成本.

'\\'整个使用而不是92.