如果要将文件的每一行保存为数组中的一行,请使用char 的二维数组:
char fileContents[NUM_LINES][LINE_LENGTH + 1]; // +1 for zero terminator
如果您不知道前面有多少行,则需要进行一些内存管理。首先,您需要分配一个初始范围:
#define INITIAL_EXTENT 20 // or some good starting point
char (*fileContents)[LINE_LENGTH + 1] = malloc( sizeof *fileContents * INITIAL_EXTENT );
if ( !fileContents )
{
// malloc failed; fatal error
fprintf( stderr, "FATAL: could not allocate memory for array\n" );
exit( EXIT_FAILURE );
}
size_t numRows = INITIAL_EXTENT; // number of rows in array
size_t rowsRead = 0; // number of rows containing data
当您从文件中读取数据时,您将检查以确保数组中有空间;如果不这样做,则需要使用 realloc 调用来扩展数组,这可能是一项昂贵的操作。一种常见的技术是每次扩展数组时都将数组的大小加倍——这可以最大限度地减少realloc 调用的总数。如果您将数组大小加倍,则风险是一些内部碎片,因为您只需要多行,但这可能是您可以分析的东西:
char tmpBuf[LINE_LENGTH + 2]; // account for newline in input buffer
while ( fgets( tmpBuf, sizeof tmpBuf, inputFile ) )
{
/**
* Check to see if you have any room left in your array; if not,
* you'll need to extend it. You'll probably want to factor this
* into its own function.
*/
if ( rowsRead == numRows )
{
/**
* Use a temporary variable for the result of realloc in case of failure
*/
char (*tmp)[LINE_LENGTH + 1] =
realloc( fileContents, sizeof *fileContents * ( 2 * numRows ) );
if ( !tmp )
{
/**
* realloc failed - we couldn't extend the array any more.
* Break out of the loop.
*/
fprintf( stderr, "ERROR: could not extend fileContents array - breaking out of loop\n" );
break;
}
/**
* Otherwise, set fileContents to point to the new, extended buffer
* and update the number of rows.
*/
fileContents = tmp;
numRows *= 2;
}
// strip the newline from the input buffer
char *newline = strchr( tmpBuf, '\n' );
if ( newline )
*newline = 0;
strcpy( fileContents[rowsRead++], tmpBuf );
}