未验证其正确性
程序代码:
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
bool getline( FILE* file, char** pbuf, size_t* pbuf_size )
{
char* buf = *pbuf;
size_t buf_size = *pbuf_size;
enum { INITIAL_SIZE = 260 };
bool result = false;
for( size_t valid_size=0; ; )
{
if( buf_size==0 || valid_size!=0 )
{
buf_size = buf_size==0 ? INITIAL_SIZE : 2*buf_size;
char* buf_new = realloc( buf, buf_size );
if( !buf_new )
return false;
buf = buf_new;
}
char* r = fgets( buf+valid_size, buf_size-valid_size, file );
if( !r )
break;
valid_size += strlen( buf+valid_size );
if( buf[valid_size-1] == '\n' )
{
buf[valid_size-1] = '\0';
result = true;
break;
}
if( feof(file) )
{
result = true;
break;
}
}
*pbuf = buf;
*pbuf_size = buf_size;
return result;
}
int main( void )
{
FILE* file = fopen( "D:/sources/Cpp005/test.txt", "rt" );
if( !file )
{
puts( "文件打开失败." );
return 1;
}
char* buf = NULL;
size_t buf_size = 0;
for( ; getline(file,&buf,&buf_size); )
{
puts( buf );
}
free( buf );
if( !feof(file) )
{
puts( "文件读取失败." );
return 2;
}
fclose( file );
return 0;
}