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

C++ 这可以在不读取文件两次的情况下完成吗?C++;,c++,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 Impleme

我在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();
}           
我只需要将名称传递给副本构造函数。 我需要将仍在文本文件中的完整路径名传递给实现文件中的MyClass::GetPath()函数

有没有一种方法可以在不读取文件两次的情况下执行此操作? 我希望你能明白我在这里想做什么。 我可能只需要回到开头或类似的地方,重新说明问题:

  • 我有一个文本文件,其中每行包含一个Windows样式的绝对路径名
  • 我需要将文件的基本名称传递给构造函数,将全名传递给另一个函数
我可以在不重读文件的情况下执行此操作吗

答案是肯定的

  • 将每行读入一个字符串(因此它包含完整路径)
  • 如有必要,去除尾随的换行符
  • 从完整路径中,创建一个新字符串,其中仅包含文件的基本名称
  • 使用basename调用构造函数
  • 使用路径名调用另一个函数
这是一种稍微多一些的字符串操作——它大大减少了文件操作,这就是性能的代价


使用
'\\'
而不是92贯穿始终。

是的,您可以将文件指针倒带到开头;请参阅seek()。不过,单遍算法会更好。这就是说——我发现这个问题很难解析,而且这个主题很难描述;当有人试图根据一行摘要来确定一个问题是否值得花时间时,使用“this”这个词是没有用的。使用(ch==92)是一个坏兆头。用法:(ch=='\\')
C:/temp/fileID
C:/temp/FileID2