//////////////////////////////////////////////////////////////////////////
// FUNCTION: GetLineAt
//
// By Giovanni Dicanio
//
//
// DESCRIPTION:
// ------------
// Reads a specified line from text file.
// The line index is 1-based.
// The line is stored into a buffer provided by the caller.
// Returns true on success, false on error.
//
//
// NOTE:
// -----
// - Works on *chars*, not WCHARs.
//
//////////////////////////////////////////////////////////////////////////
bool GetLineAt(
const char * filename,
char * buffer,
int bufferSize,
int lineCount
)
{
// Check input parameters
ASSERT( filename != NULL );
ASSERT( buffer != NULL );
ASSERT( bufferSize > 0 );
ASSERT( lineCount > 0 );
// Open the file
FILE * file = fopen( filename, "r" );
if ( file == NULL )
return false;
// Loop until you find the specified line, or EOF is reached
int lineIndex = 1; // Count lines (1-based)
bool ok = false; // Function succeeded ?
while ( fgets( buffer, bufferSize, file ) )
{
if ( lineIndex == lineCount )
{
// Successfully read specified line
ok = true;
break;
}
// Update line counter
lineIndex++;
}
// On error, clear the buffer, so we don't have spurious data
// stored in it.
if ( ! ok )
{
memset( buffer, 0, bufferSize );
}
// Close file
fclose( file );
file = NULL;
// Return result of operations
return ok;
}
//
// ** Can use like so: **
//
//
//
// static const int bufSize = 120;
// char buffer[ bufSize ];
//
// // Get 4th line from file
// bool ok = GetLineAt( "D:\\test.txt", buffer, bufSize, 4 );
//
//
//
Text file Source (historic): geocities.com/giovanni.dicanio/vc
geocities.com/giovanni.dicanio(to report bad content: archivehelp @ gmail)
|
|
|
|
|