I need to write a function to read a string from a file with the following conditions

  • the string must be read entirely in one pass before the EOF or EOL character
  • it is impossible to allocate in advance a large buffer in which the readable string is guaranteed to be placed
  • realloc() cannot be used

Nothing better, moreover, how to read character by character and shove it onto the stack, did not invent it. Are there any other options? Maybe using string.h ?

  • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin

2 answers 2

For example. LIST_ITEM_SIZE - maximum allowed buffer size.

 size_t read_line( list *storage, FILE *file ) { char buf[LIST_ITEM_SIZE]; size_t size = 0; while( fgets( buf, sizeof(buf)-1, file ) ) { size_t readed = strlen(buf); add_to_list( storage, buf, readed ); size += readed; } return size; } 

Although, of course, it is easier to first allocate a small buffer and stretch it with malloc() / strcpy() as you read.

  • omg, please read the condition again - Gagik Palikyan
  • one
    Read it. I see no contradiction. - PinkTux
  1. mmap
  2. allocate one buffer equal to or multiple to the file system I / O block size, typical 4K, and use it to store data. See if the API of your OS does not have the ability to work on callback - so that the OS, after finishing reading into the buffer, will pull your own analysis function CALLBACK parser(char*); , useful for "smooth" work in multitasking OS. If not, implement the normal reading cycle while not EOF { os_read(buf); parse(buf); } while not EOF { os_read(buf); parse(buf); }