Can I do this without reading the file twice? C ++

What I am doing here in main.cpp is reading a text file twice: once to remove the "\" from each pathname and again to specify the original filename in SetPath () in my implementation file.

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

      

The text file has the following format:

C:/temp/fileID
C:/temp/FileID2

      

I only need to pass the name to the copy constructor. I need to pass the fully qualified pathname, which is still in the text file, to MyClass :: GetPath () in my implementation file.

Is there a way to do this without reading the file twice? Hope you can see what I'm trying to do here. i might just rewind to the beginning or something

0


a source to share


1 answer


Repeating the problem:

  • I have a text file where each line contains an absolute Windows style pathname.
  • I need to pass the base filename to the constructor and the fully qualified name of another function.

Can I do this without rereading the file?

The answer is yes.



  • Read each line in a line (so that it contains the full path).
  • Separate the trailing newline if necessary.
  • From the full path, create a new line containing only the base filename.
  • Calling a constructor with a base name.
  • Call another function with the path name.

This is a slightly more inline manipulation - it is significantly less file manipulation, and it is exactly worth the cost.

Use '\\'

, not 92.

+8


a source







All Articles