daily pastebin goal
49%
SHARE
TWEET

Untitled

a guest Oct 23rd, 2018 76 Never
Upgrade to PRO!
ENDING IN00days00hours00mins00secs
  1. har *
  2. readUntilEOL( FILE *line )
  3. {
  4.     int cycle_counter = 1;
  5.     char *buffer = NULL;
  6.     char *buffer_saver = NULL; // if after realloc we lose memory
  7.     if ( line == NULL ) {
  8.         perror( "Empty file!" );
  9.         return NULL;
  10.     } else {
  11.         const unsigned int BUFFER_SIZE = 1000000;
  12.         buffer = calloc( BUFFER_SIZE, sizeof( *buffer ) );
  13.         if ( buffer == NULL ) {
  14.              perror( "Not enough memory for calloc" );
  15.              return NULL;
  16.         }
  17.         do {
  18.             buffer_saver = fgets( buffer + ( cycle_counter - 1 ) * ( BUFFER_SIZE - 1 ), BUFFER_SIZE, line );
  19.             if ( buffer_saver == NULL ) {  // third  variant
  20.                 return buffer;
  21.             }
  22.             if ( ( strlen( buffer ) == 1 ) && ( buffer[0] == '\n' ) ) {  // if it's blank string
  23.                 free( buffer );
  24.                 return NULL;
  25.             }
  26.             if ( buffer[ strlen( buffer ) - 1 ] == '\n' ) {
  27.                     return buffer;
  28.             }
  29.             cycle_counter++;
  30.             buffer_saver = realloc( buffer, 1 + cycle_counter * ( BUFFER_SIZE - 1 ) * sizeof( *buffer ) );
  31.             // we checked, that it's not EOL and EOF earlier, so we have at least one more symbol in line, so we have at least one byte of memory
  32.             if ( buffer_saver == NULL ) {
  33.                 int memory_size = 1;
  34.                 buffer_saver = realloc( buffer,  memory_size + 1 + ( BUFFER_SIZE - 1 ) * ( cycle_counter - 1 ) * sizeof( *buffer )  );
  35.                 while ( buffer_saver != NULL ) {
  36.                     buffer_saver = fgets( buffer + memory_size + ( cycle_counter - 1 ) * ( BUFFER_SIZE - 1 ), 1, line );
  37.                     if ( buffer_saver == NULL ) {  // third  variant
  38.                         return buffer;
  39.                     }
  40.                     if ( buffer[ strlen( buffer ) - 1 ] == '\n' ) {
  41.                         return buffer;
  42.                     }
  43.                     memory_size++;
  44.                     buffer_saver = realloc( buffer, ( memory_size + 1 + ( BUFFER_SIZE - 1 ) * ( cycle_counter - 1 ) * sizeof( *buffer ) ) );
  45.                 }
  46.                 perror( "Not enough memory for realloc." );
  47.                 free( buffer );
  48.                 return NULL;
  49.             }
  50.             buffer = buffer_saver;
  51.  
  52.         } while ( 1 );
  53.  
  54.     }
  55. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top