diff -r a5eabd407774 -r d5d6ab809ad3 docs/src/modules.md --- a/docs/src/modules.md Wed May 09 15:04:15 2018 +0200 +++ b/docs/src/modules.md Wed May 09 20:15:10 2018 +0200 @@ -108,6 +108,80 @@ See the documentation of the macro constants in the header file for more information. +### Add line numbers to a file + +When reading a file line by line, you have three options: first, you could limit +the maximum supported line length. +Second, you allocate a god buffer large +enough for the most lines a text file could have. +And third, undoubtedly the best option, you start with a small buffer, which +adjusts on demand. +An `UcxBuffer` can be created to do just that for you. +Just pass the `UCX_BUFFER_AUTOEXTEND` option to the initialization function. +Here is a full working program, which adds line numbers to a file. +```C +#include +#include +#include + +int main(int argc, char** argv) { + + if (argc != 2) { + fprintf(stderr, "Usage: %s \n", argv[0]); + return 1; + } + + FILE* input = fopen(argv[1], "r"); + if (!input) { + perror("Canno read input"); + return 1; + } + + const size_t chunksize = 256; + + UcxBuffer* linebuf = + ucx_buffer_new( + NULL, // the buffer should manage the memory area for us + chunksize, // initial buffer size should be the chunk size + UCX_BUFFER_AUTOEXTEND); // the buffer will grow when necessary + + size_t lineno = 1; + do { + // read line chunk + size_t read = ucx_stream_ncopy( + input, linebuf, fread, ucx_buffer_write, chunksize); + if (read == 0) break; + + // handle line endings + do { + sstr_t bufstr = ucx_buffer_to_sstr(linebuf); + sstr_t nl = sstrchr(bufstr, '\n'); + if (nl.length == 0) break; + + size_t linelen = bufstr.length - nl.length; + sstr_t linestr = sstrsubsl(bufstr, 0, linelen); + + printf("%zu: %" PRIsstr "\n", lineno++, SFMT(linestr)); + + // shift the buffer to the next line + ucx_buffer_shift_left(linebuf, linelen+1); + } while(1); + + } while(1); + + // print the 'noeol' line, if any + sstr_t lastline = ucx_buffer_to_sstr(linebuf); + if (lastline.length > 0) { + printf("%zu: %" PRIsstr, lineno, SFMT(lastline)); + } + + fclose(input); + ucx_buffer_free(linebuf); + + return 0; +} +``` + ## List *Header file:* [list.h](api/list_8h.html)