tags:

views:

253

answers:

1

Hi, What im doing here in main.cpp is reading a text file twice: once to remove the '\' from each path name, and again to supply the original name of the file to the 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 is of this format:

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

I need to pass just the name to a copy constructor. I need to pass the full path name which is still in the text file to a MyClass::GetPath() function in my Implementation file.

Is there a way to do this without reading the file twice? I hope you can see what im trying to do here. i can probably just rewind to the beginning or something like that

+7  A: 

Restating the problem:

  • I have a text file where each line contains a Windows-style absolute path name.
  • I need to pass the basename of the file to a constructor and the full name to another function.

Can I do this without rereading the file?

The answer is yes.

  • Read each line into a string (so it contains the full path).
  • If necessary, strip the trailing newline.
  • From the full path, create a new string containing just the basename of the file.
  • Call the constructor with the basename.
  • Call the other function with the pathname.

This is slightly more string manipulation - it is vastly less file manipulation, and that is what costs performance.

Use '\\' rather than 92 throughout.

Jonathan Leffler
+1 for clear question :)
stefanB